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"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
61 #include "TexStream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/PreviewLoader.h"
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
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);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
358 // We are in our own directory. Why bother to mangle name?
359 // In fact I wrote this code to circumvent a problematic behaviour
360 // (bug?) of EMX mkstemp().
361 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
362 convert<string>(count++));
364 if (!tmpfl.createDirectory(0777)) {
365 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
366 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
367 from_utf8(tmpfl.absFileName())));
373 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
374 Buffer const * cloned_buffer)
375 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
376 internal_buffer(false), read_only(readonly_), filename(file),
377 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
378 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
379 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
380 cite_labels_valid_(false), preview_loader_(0),
381 cloned_buffer_(cloned_buffer), clone_list_(0),
382 doing_export(false), parent_buffer(0)
384 if (!cloned_buffer_) {
385 temppath = createBufferTmpDir();
386 lyxvc.setBuffer(owner_);
388 wa_ = new frontend::WorkAreaManager;
391 temppath = cloned_buffer_->d->temppath;
392 file_fully_loaded = true;
393 params = cloned_buffer_->d->params;
394 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
395 bibinfo_ = cloned_buffer_->d->bibinfo_;
396 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
397 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
398 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
399 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
400 unnamed = cloned_buffer_->d->unnamed;
401 internal_buffer = cloned_buffer_->d->internal_buffer;
405 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
406 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
408 LYXERR(Debug::INFO, "Buffer::Buffer()");
410 d->inset = new InsetText(*cloned_buffer->d->inset);
411 d->inset->setBuffer(*this);
412 // FIXME: optimize this loop somewhat, maybe by creating a new
413 // general recursive Inset::setId().
414 DocIterator it = doc_iterator_begin(this);
415 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
416 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
417 it.paragraph().setId(cloned_it.paragraph().id());
419 d->inset = new InsetText(this);
420 d->inset->setAutoBreakRows(true);
421 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
427 LYXERR(Debug::INFO, "Buffer::~Buffer()");
428 // here the buffer should take care that it is
429 // saved properly, before it goes into the void.
431 // GuiView already destroyed
435 // No need to do additional cleanups for internal buffer.
441 // this is in case of recursive includes: we won't try to delete
442 // ourselves as a child.
443 d->clone_list_->erase(this);
444 // loop over children
445 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
446 Impl::BufferPositionMap::iterator end = d->children_positions.end();
447 for (; it != end; ++it) {
448 Buffer * child = const_cast<Buffer *>(it->first);
449 if (d->clone_list_->erase(child))
452 // if we're the master buffer, then we should get rid of the list
455 // if this is not empty, we have leaked something. worse, one of the
456 // children still has a reference to this list.
457 LASSERT(d->clone_list_->empty(), /* */);
458 list<CloneList *>::iterator it =
459 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
460 LASSERT(it != cloned_buffers.end(), /* */);
461 cloned_buffers.erase(it);
462 delete d->clone_list_;
464 // FIXME Do we really need to do this right before we delete d?
465 // clear references to children in macro tables
466 d->children_positions.clear();
467 d->position_to_children.clear();
469 // loop over children
470 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
471 Impl::BufferPositionMap::iterator end = d->children_positions.end();
472 for (; it != end; ++it) {
473 Buffer * child = const_cast<Buffer *>(it->first);
474 if (theBufferList().isLoaded(child))
475 theBufferList().releaseChild(this, child);
479 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
480 msg += emergencyWrite();
481 Alert::warning(_("Attempting to close changed document!"), msg);
484 // FIXME Do we really need to do this right before we delete d?
485 // clear references to children in macro tables
486 d->children_positions.clear();
487 d->position_to_children.clear();
489 if (!d->temppath.destroyDirectory()) {
490 Alert::warning(_("Could not remove temporary directory"),
491 bformat(_("Could not remove the temporary directory %1$s"),
492 from_utf8(d->temppath.absFileName())));
501 Buffer * Buffer::cloneFromMaster() const
504 cloned_buffers.push_back(new CloneList);
505 CloneList * clones = cloned_buffers.back();
507 masterBuffer()->cloneWithChildren(bufmap, clones);
509 // make sure we got cloned
510 BufferMap::const_iterator bit = bufmap.find(this);
511 LASSERT(bit != bufmap.end(), return 0);
512 Buffer * cloned_buffer = bit->second;
514 return cloned_buffer;
518 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
520 // have we already been cloned?
521 if (bufmap.find(this) != bufmap.end())
524 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
526 // The clone needs its own DocumentClass, since running updateBuffer() will
527 // modify it, and we would otherwise be sharing it with the original Buffer.
528 buffer_clone->params().makeDocumentClass();
530 cap::switchBetweenClasses(
531 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
532 static_cast<InsetText &>(buffer_clone->inset()), el);
534 bufmap[this] = buffer_clone;
535 clones->insert(buffer_clone);
536 buffer_clone->d->clone_list_ = clones;
537 buffer_clone->d->macro_lock = true;
538 buffer_clone->d->children_positions.clear();
540 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
541 // math macro caches need to be rethought and simplified.
542 // I am not sure wether we should handle Buffer cloning here or in BufferList.
543 // Right now BufferList knows nothing about buffer clones.
544 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
545 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
546 for (; it != end; ++it) {
547 DocIterator dit = it->first.clone(buffer_clone);
548 dit.setBuffer(buffer_clone);
549 Buffer * child = const_cast<Buffer *>(it->second.second);
551 child->cloneWithChildren(bufmap, clones);
552 BufferMap::iterator const bit = bufmap.find(child);
553 LASSERT(bit != bufmap.end(), continue);
554 Buffer * child_clone = bit->second;
556 Inset * inset = dit.nextInset();
557 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
558 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
559 inset_inc->setChildBuffer(child_clone);
560 child_clone->d->setParent(buffer_clone);
561 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
562 buffer_clone->setChild(dit, child_clone);
564 buffer_clone->d->macro_lock = false;
569 Buffer * Buffer::cloneBufferOnly() const {
570 cloned_buffers.push_back(new CloneList);
571 CloneList * clones = cloned_buffers.back();
572 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
574 // The clone needs its own DocumentClass, since running updateBuffer() will
575 // modify it, and we would otherwise be sharing it with the original Buffer.
576 buffer_clone->params().makeDocumentClass();
578 cap::switchBetweenClasses(
579 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
580 static_cast<InsetText &>(buffer_clone->inset()), el);
582 clones->insert(buffer_clone);
583 buffer_clone->d->clone_list_ = clones;
585 // we won't be cloning the children
586 buffer_clone->d->children_positions.clear();
591 bool Buffer::isClone() const
593 return d->cloned_buffer_;
597 void Buffer::changed(bool update_metrics) const
600 d->wa_->redrawAll(update_metrics);
604 frontend::WorkAreaManager & Buffer::workAreaManager() const
606 LASSERT(d->wa_, /**/);
611 Text & Buffer::text() const
613 return d->inset->text();
617 Inset & Buffer::inset() const
623 BufferParams & Buffer::params()
629 BufferParams const & Buffer::params() const
635 ParagraphList & Buffer::paragraphs()
637 return text().paragraphs();
641 ParagraphList const & Buffer::paragraphs() const
643 return text().paragraphs();
647 LyXVC & Buffer::lyxvc()
653 LyXVC const & Buffer::lyxvc() const
659 string const Buffer::temppath() const
661 return d->temppath.absFileName();
665 TexRow & Buffer::texrow()
671 TexRow const & Buffer::texrow() const
677 TocBackend & Buffer::tocBackend() const
679 return d->toc_backend;
683 Undo & Buffer::undo()
689 void Buffer::setChild(DocIterator const & dit, Buffer * child)
691 d->children_positions[child] = dit;
695 string Buffer::latexName(bool const no_path) const
697 FileName latex_name =
698 makeLatexName(d->exportFileName());
699 return no_path ? latex_name.onlyFileName()
700 : latex_name.absFileName();
704 FileName Buffer::Impl::exportFileName() const
706 docstring const branch_suffix =
707 params.branchlist().getFileNameSuffix();
708 if (branch_suffix.empty())
711 string const name = filename.onlyFileNameWithoutExt()
712 + to_utf8(branch_suffix);
713 FileName res(filename.onlyPath().absFileName() + "/" + name);
714 res.changeExtension(filename.extension());
720 string Buffer::logName(LogType * type) const
722 string const filename = latexName(false);
724 if (filename.empty()) {
730 string const path = temppath();
732 FileName const fname(addName(temppath(),
733 onlyFileName(changeExtension(filename,
736 // FIXME: how do we know this is the name of the build log?
737 FileName const bname(
738 addName(path, onlyFileName(
739 changeExtension(filename,
740 formats.extension(params().bufferFormat()) + ".out"))));
742 // Also consider the master buffer log file
743 FileName masterfname = fname;
745 if (masterBuffer() != this) {
746 string const mlogfile = masterBuffer()->logName(&mtype);
747 masterfname = FileName(mlogfile);
750 // If no Latex log or Build log is newer, show Build log
751 if (bname.exists() &&
752 ((!fname.exists() && !masterfname.exists())
753 || (fname.lastModified() < bname.lastModified()
754 && masterfname.lastModified() < bname.lastModified()))) {
755 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
758 return bname.absFileName();
759 // If we have a newer master file log or only a master log, show this
760 } else if (fname != masterfname
761 && (!fname.exists() && (masterfname.exists()
762 || fname.lastModified() < masterfname.lastModified()))) {
763 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
766 return masterfname.absFileName();
768 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
771 return fname.absFileName();
775 void Buffer::setReadonly(bool const flag)
777 if (d->read_only != flag) {
784 void Buffer::setFileName(FileName const & fname)
786 bool const changed = fname != d->filename;
789 lyxvc().file_found_hook(fname);
790 setReadonly(d->filename.isReadOnly());
796 int Buffer::readHeader(Lexer & lex)
798 int unknown_tokens = 0;
800 int begin_header_line = -1;
802 // Initialize parameters that may be/go lacking in header:
803 params().branchlist().clear();
804 params().preamble.erase();
805 params().options.erase();
806 params().master.erase();
807 params().float_placement.erase();
808 params().paperwidth.erase();
809 params().paperheight.erase();
810 params().leftmargin.erase();
811 params().rightmargin.erase();
812 params().topmargin.erase();
813 params().bottommargin.erase();
814 params().headheight.erase();
815 params().headsep.erase();
816 params().footskip.erase();
817 params().columnsep.erase();
818 params().fonts_cjk.erase();
819 params().listings_params.clear();
820 params().clearLayoutModules();
821 params().clearRemovedModules();
822 params().clearIncludedChildren();
823 params().pdfoptions().clear();
824 params().indiceslist().clear();
825 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
826 params().isbackgroundcolor = false;
827 params().fontcolor = RGBColor(0, 0, 0);
828 params().isfontcolor = false;
829 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
830 params().boxbgcolor = RGBColor(0xFF, 0, 0);
831 params().html_latex_start.clear();
832 params().html_latex_end.clear();
833 params().html_math_img_scale = 1.0;
834 params().output_sync_macro.erase();
835 params().local_layout.clear();
837 for (int i = 0; i < 4; ++i) {
838 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
839 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
842 ErrorList & errorList = d->errorLists["Parse"];
851 if (token == "\\end_header")
855 if (token == "\\begin_header") {
856 begin_header_line = line;
860 LYXERR(Debug::PARSER, "Handling document header token: `"
863 string unknown = params().readToken(lex, token, d->filename.onlyPath());
864 if (!unknown.empty()) {
865 if (unknown[0] != '\\' && token == "\\textclass") {
866 Alert::warning(_("Unknown document class"),
867 bformat(_("Using the default document class, because the "
868 "class %1$s is unknown."), from_utf8(unknown)));
871 docstring const s = bformat(_("Unknown token: "
875 errorList.push_back(ErrorItem(_("Document header error"),
880 if (begin_header_line) {
881 docstring const s = _("\\begin_header is missing");
882 errorList.push_back(ErrorItem(_("Document header error"),
886 params().makeDocumentClass();
888 return unknown_tokens;
893 // changed to be public and have one parameter
894 // Returns true if "\end_document" is not read (Asger)
895 bool Buffer::readDocument(Lexer & lex)
897 ErrorList & errorList = d->errorLists["Parse"];
900 // remove dummy empty par
901 paragraphs().clear();
903 if (!lex.checkFor("\\begin_document")) {
904 docstring const s = _("\\begin_document is missing");
905 errorList.push_back(ErrorItem(_("Document header error"),
911 if (params().outputChanges) {
912 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
913 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
914 LaTeXFeatures::isAvailable("xcolor");
916 if (!dvipost && !xcolorulem) {
917 Alert::warning(_("Changes not shown in LaTeX output"),
918 _("Changes will not be highlighted in LaTeX output, "
919 "because neither dvipost nor xcolor/ulem are installed.\n"
920 "Please install these packages or redefine "
921 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
922 } else if (!xcolorulem) {
923 Alert::warning(_("Changes not shown in LaTeX output"),
924 _("Changes will not be highlighted in LaTeX output "
925 "when using pdflatex, because xcolor and ulem are not installed.\n"
926 "Please install both packages or redefine "
927 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
931 if (!params().master.empty()) {
932 FileName const master_file = makeAbsPath(params().master,
933 onlyPath(absFileName()));
934 if (isLyXFileName(master_file.absFileName())) {
936 checkAndLoadLyXFile(master_file, true);
938 // necessary e.g. after a reload
939 // to re-register the child (bug 5873)
940 // FIXME: clean up updateMacros (here, only
941 // child registering is needed).
942 master->updateMacros();
943 // set master as master buffer, but only
944 // if we are a real child
945 if (master->isChild(this))
947 // if the master is not fully loaded
948 // it is probably just loading this
949 // child. No warning needed then.
950 else if (master->isFullyLoaded())
951 LYXERR0("The master '"
953 << "' assigned to this document ("
955 << ") does not include "
956 "this document. Ignoring the master assignment.");
961 // assure we have a default index
962 params().indiceslist().addDefault(B_("Index"));
965 bool const res = text().read(lex, errorList, d->inset);
967 // inform parent buffer about local macros
969 Buffer const * pbuf = parent();
970 UserMacroSet::const_iterator cit = usermacros.begin();
971 UserMacroSet::const_iterator end = usermacros.end();
972 for (; cit != end; ++cit)
973 pbuf->usermacros.insert(*cit);
977 updateMacroInstances(InternalUpdate);
982 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
984 Format const * fmt = formats.getFormat(format);
987 // It is important to use the correct extension here, since some
988 // converters create a wrong output file otherwise (e.g. html2latex)
989 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
990 FileName const name(tempfile.name());
991 ofdocstream os(name.toFilesystemEncoding().c_str());
992 bool const success = (os << contents);
995 bool converted = false;
997 params().compressed = false;
999 // remove dummy empty par
1000 paragraphs().clear();
1002 converted = importFile(format, name, errorList);
1011 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1013 if (!theConverters().isReachable(format, "lyx"))
1016 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1017 FileName const lyx(tempfile.name());
1018 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1019 return readFile(lyx) == ReadSuccess;
1025 bool Buffer::readString(string const & s)
1027 params().compressed = false;
1030 istringstream is(s);
1032 FileName const fn = FileName::tempName("Buffer_readString");
1035 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1037 if (success && file_format != LYX_FORMAT) {
1038 // We need to call lyx2lyx, so write the input to a file
1039 ofstream os(fn.toFilesystemEncoding().c_str());
1042 // lyxvc in readFile
1043 if (readFile(fn) != ReadSuccess)
1047 if (readDocument(lex))
1055 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1059 if (!lex.setFile(fname)) {
1060 Alert::error(_("File Not Found"),
1061 bformat(_("Unable to open file `%1$s'."),
1062 from_utf8(fn.absFileName())));
1063 return ReadFileNotFound;
1067 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1068 if (ret_plf != ReadSuccess)
1071 if (file_format != LYX_FORMAT) {
1073 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1074 if (ret_clf != ReadSuccess)
1076 return readFile(tmpFile);
1079 // FIXME: InsetInfo needs to know whether the file is under VCS
1080 // during the parse process, so this has to be done before.
1081 lyxvc().file_found_hook(d->filename);
1083 if (readDocument(lex)) {
1084 Alert::error(_("Document format failure"),
1085 bformat(_("%1$s ended unexpectedly, which means"
1086 " that it is probably corrupted."),
1087 from_utf8(fn.absFileName())));
1088 return ReadDocumentFailure;
1091 d->file_fully_loaded = true;
1092 d->read_only = !d->filename.isWritable();
1093 params().compressed = formats.isZippedFile(d->filename);
1099 bool Buffer::isFullyLoaded() const
1101 return d->file_fully_loaded;
1105 void Buffer::setFullyLoaded(bool value)
1107 d->file_fully_loaded = value;
1111 PreviewLoader * Buffer::loader() const
1113 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1115 if (!d->preview_loader_)
1116 d->preview_loader_ = new PreviewLoader(*this);
1117 return d->preview_loader_;
1121 void Buffer::removePreviews() const
1123 delete d->preview_loader_;
1124 d->preview_loader_ = 0;
1128 void Buffer::updatePreviews() const
1130 PreviewLoader * ploader = loader();
1134 InsetIterator it = inset_iterator_begin(*d->inset);
1135 InsetIterator const end = inset_iterator_end(*d->inset);
1136 for (; it != end; ++it)
1137 it->addPreview(it, *ploader);
1139 ploader->startLoading();
1143 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1144 FileName const & fn, int & file_format) const
1146 if(!lex.checkFor("\\lyxformat")) {
1147 Alert::error(_("Document format failure"),
1148 bformat(_("%1$s is not a readable LyX document."),
1149 from_utf8(fn.absFileName())));
1150 return ReadNoLyXFormat;
1156 // LyX formats 217 and earlier were written as 2.17. This corresponds
1157 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1158 // these cases. See also: www.lyx.org/trac/changeset/1313.
1159 size_t dot = tmp_format.find_first_of(".,");
1160 if (dot != string::npos)
1161 tmp_format.erase(dot, 1);
1163 file_format = convert<int>(tmp_format);
1168 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1169 FileName & tmpfile, int from_format)
1171 tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1172 if(tmpfile.empty()) {
1173 Alert::error(_("Conversion failed"),
1174 bformat(_("%1$s is from a different"
1175 " version of LyX, but a temporary"
1176 " file for converting it could"
1177 " not be created."),
1178 from_utf8(fn.absFileName())));
1179 return LyX2LyXNoTempFile;
1182 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1183 if (lyx2lyx.empty()) {
1184 Alert::error(_("Conversion script not found"),
1185 bformat(_("%1$s is from a different"
1186 " version of LyX, but the"
1187 " conversion script lyx2lyx"
1188 " could not be found."),
1189 from_utf8(fn.absFileName())));
1190 return LyX2LyXNotFound;
1194 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1195 ostringstream command;
1196 command << os::python()
1197 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1198 << " -t " << convert<string>(LYX_FORMAT)
1199 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1200 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1201 string const command_str = command.str();
1203 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1205 cmd_ret const ret = runCommand(command_str);
1206 if (ret.first != 0) {
1207 if (from_format < LYX_FORMAT) {
1208 Alert::error(_("Conversion script failed"),
1209 bformat(_("%1$s is from an older version"
1210 " of LyX and the lyx2lyx script"
1211 " failed to convert it."),
1212 from_utf8(fn.absFileName())));
1213 return LyX2LyXOlderFormat;
1215 Alert::error(_("Conversion script failed"),
1216 bformat(_("%1$s is from a newer version"
1217 " of LyX and the lyx2lyx script"
1218 " failed to convert it."),
1219 from_utf8(fn.absFileName())));
1220 return LyX2LyXNewerFormat;
1227 // Should probably be moved to somewhere else: BufferView? GuiView?
1228 bool Buffer::save() const
1230 docstring const file = makeDisplayPath(absFileName(), 20);
1231 d->filename.refresh();
1233 // check the read-only status before moving the file as a backup
1234 if (d->filename.exists()) {
1235 bool const read_only = !d->filename.isWritable();
1237 Alert::warning(_("File is read-only"),
1238 bformat(_("The file %1$s cannot be written because it "
1239 "is marked as read-only."), file));
1244 // ask if the disk file has been externally modified (use checksum method)
1245 if (fileName().exists() && isExternallyModified(checksum_method)) {
1247 bformat(_("Document %1$s has been externally modified. "
1248 "Are you sure you want to overwrite this file?"), file);
1249 int const ret = Alert::prompt(_("Overwrite modified file?"),
1250 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1255 // We don't need autosaves in the immediate future. (Asger)
1256 resetAutosaveTimers();
1258 FileName backupName;
1259 bool madeBackup = false;
1261 // make a backup if the file already exists
1262 if (lyxrc.make_backup && fileName().exists()) {
1263 backupName = FileName(absFileName() + '~');
1264 if (!lyxrc.backupdir_path.empty()) {
1265 string const mangledName =
1266 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1267 backupName = FileName(addName(lyxrc.backupdir_path,
1271 // Except file is symlink do not copy because of #6587.
1272 // Hard links have bad luck.
1273 if (fileName().isSymLink())
1274 madeBackup = fileName().copyTo(backupName);
1276 madeBackup = fileName().moveTo(backupName);
1279 Alert::error(_("Backup failure"),
1280 bformat(_("Cannot create backup file %1$s.\n"
1281 "Please check whether the directory exists and is writable."),
1282 from_utf8(backupName.absFileName())));
1283 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1287 if (writeFile(d->filename)) {
1291 // Saving failed, so backup is not backup
1293 backupName.moveTo(d->filename);
1299 bool Buffer::writeFile(FileName const & fname) const
1301 if (d->read_only && fname == d->filename)
1304 bool retval = false;
1306 docstring const str = bformat(_("Saving document %1$s..."),
1307 makeDisplayPath(fname.absFileName()));
1310 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1312 if (params().compressed) {
1313 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1314 retval = ofs && write(ofs);
1316 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1317 retval = ofs && write(ofs);
1321 message(str + _(" could not write file!"));
1326 // removeAutosaveFile();
1329 message(str + _(" done."));
1335 docstring Buffer::emergencyWrite()
1337 // No need to save if the buffer has not changed.
1341 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1343 docstring user_message = bformat(
1344 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1346 // We try to save three places:
1347 // 1) Same place as document. Unless it is an unnamed doc.
1349 string s = absFileName();
1352 if (writeFile(FileName(s))) {
1354 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1355 return user_message;
1357 user_message += " " + _("Save failed! Trying again...\n");
1361 // 2) In HOME directory.
1362 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1364 lyxerr << ' ' << s << endl;
1365 if (writeFile(FileName(s))) {
1367 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1368 return user_message;
1371 user_message += " " + _("Save failed! Trying yet again...\n");
1373 // 3) In "/tmp" directory.
1374 // MakeAbsPath to prepend the current
1375 // drive letter on OS/2
1376 s = addName(package().temp_dir().absFileName(), absFileName());
1378 lyxerr << ' ' << s << endl;
1379 if (writeFile(FileName(s))) {
1381 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1382 return user_message;
1385 user_message += " " + _("Save failed! Bummer. Document is lost.");
1388 return user_message;
1392 bool Buffer::write(ostream & ofs) const
1395 // Use the standard "C" locale for file output.
1396 ofs.imbue(locale::classic());
1399 // The top of the file should not be written by params().
1401 // write out a comment in the top of the file
1402 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1403 << " created this file. For more info see http://www.lyx.org/\n"
1404 << "\\lyxformat " << LYX_FORMAT << "\n"
1405 << "\\begin_document\n";
1407 /// For each author, set 'used' to true if there is a change
1408 /// by this author in the document; otherwise set it to 'false'.
1409 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1410 AuthorList::Authors::const_iterator a_end = params().authors().end();
1411 for (; a_it != a_end; ++a_it)
1412 a_it->setUsed(false);
1414 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1415 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1416 for ( ; it != end; ++it)
1417 it->checkAuthors(params().authors());
1419 // now write out the buffer parameters.
1420 ofs << "\\begin_header\n";
1421 params().writeFile(ofs);
1422 ofs << "\\end_header\n";
1425 ofs << "\n\\begin_body\n";
1427 ofs << "\n\\end_body\n";
1429 // Write marker that shows file is complete
1430 ofs << "\\end_document" << endl;
1432 // Shouldn't really be needed....
1435 // how to check if close went ok?
1436 // Following is an attempt... (BE 20001011)
1438 // good() returns false if any error occured, including some
1439 // formatting error.
1440 // bad() returns true if something bad happened in the buffer,
1441 // which should include file system full errors.
1446 lyxerr << "File was not closed properly." << endl;
1453 bool Buffer::makeLaTeXFile(FileName const & fname,
1454 string const & original_path,
1455 OutputParams const & runparams_in,
1456 OutputWhat output) const
1458 OutputParams runparams = runparams_in;
1460 // This is necessary for LuaTeX/XeTeX with tex fonts.
1461 // See FIXME in BufferParams::encoding()
1462 if (runparams.isFullUnicode())
1463 runparams.encoding = encodings.fromLyXName("utf8-plain");
1465 string const encoding = runparams.encoding->iconvName();
1466 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1469 try { ofs.reset(encoding); }
1470 catch (iconv_codecvt_facet_exception const & e) {
1471 lyxerr << "Caught iconv exception: " << e.what() << endl;
1472 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1473 "verify that the support software for your encoding (%1$s) is "
1474 "properly installed"), from_ascii(encoding)));
1477 if (!openFileWrite(ofs, fname))
1480 //TexStream ts(ofs.rdbuf(), &texrow());
1481 ErrorList & errorList = d->errorLists["Export"];
1483 bool failed_export = false;
1484 otexstream os(ofs, d->texrow);
1486 // make sure we are ready to export
1487 // this needs to be done before we validate
1488 // FIXME Do we need to do this all the time? I.e., in children
1489 // of a master we are exporting?
1491 updateMacroInstances(OutputUpdate);
1494 os.texrow().reset();
1495 writeLaTeXSource(os, original_path, runparams, output);
1497 catch (EncodingException const & e) {
1498 odocstringstream ods;
1499 ods.put(e.failed_char);
1501 oss << "0x" << hex << e.failed_char << dec;
1502 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1503 " (code point %2$s)"),
1504 ods.str(), from_utf8(oss.str()));
1505 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1506 "representable in the chosen encoding.\n"
1507 "Changing the document encoding to utf8 could help."),
1508 e.par_id, e.pos, e.pos + 1));
1509 failed_export = true;
1511 catch (iconv_codecvt_facet_exception const & e) {
1512 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1513 _(e.what()), -1, 0, 0));
1514 failed_export = true;
1516 catch (exception const & e) {
1517 errorList.push_back(ErrorItem(_("conversion failed"),
1518 _(e.what()), -1, 0, 0));
1519 failed_export = true;
1522 lyxerr << "Caught some really weird exception..." << endl;
1528 failed_export = true;
1529 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1533 return !failed_export;
1537 void Buffer::writeLaTeXSource(otexstream & os,
1538 string const & original_path,
1539 OutputParams const & runparams_in,
1540 OutputWhat output) const
1542 // The child documents, if any, shall be already loaded at this point.
1544 OutputParams runparams = runparams_in;
1546 // If we are compiling a file standalone, even if this is the
1547 // child of some other buffer, let's cut the link here, so the
1548 // file is really independent and no concurring settings from
1549 // the master (e.g. branch state) interfere (see #8100).
1550 if (!runparams.is_child)
1551 d->ignore_parent = true;
1553 // Classify the unicode characters appearing in math insets
1554 Encodings::initUnicodeMath(*this);
1556 // validate the buffer.
1557 LYXERR(Debug::LATEX, " Validating buffer...");
1558 LaTeXFeatures features(*this, params(), runparams);
1560 runparams.use_polyglossia = features.usePolyglossia();
1561 LYXERR(Debug::LATEX, " Buffer validation done.");
1563 bool const output_preamble =
1564 output == FullSource || output == OnlyPreamble;
1565 bool const output_body =
1566 output == FullSource || output == OnlyBody;
1568 // The starting paragraph of the coming rows is the
1569 // first paragraph of the document. (Asger)
1570 if (output_preamble && runparams.nice) {
1571 os << "%% LyX " << lyx_version << " created this file. "
1572 "For more info, see http://www.lyx.org/.\n"
1573 "%% Do not edit unless you really know what "
1576 LYXERR(Debug::INFO, "lyx document header finished");
1578 // There are a few differences between nice LaTeX and usual files:
1579 // usual files have \batchmode and special input@path to allow
1580 // inclusion of figures specified by an explicitly relative path
1581 // (i.e., a path starting with './' or '../') with either \input or
1582 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1583 // input@path is set when the actual parameter original_path is set.
1584 // This is done for usual tex-file, but not for nice-latex-file.
1585 // (Matthias 250696)
1586 // Note that input@path is only needed for something the user does
1587 // in the preamble, included .tex files or ERT, files included by
1588 // LyX work without it.
1589 if (output_preamble) {
1590 if (!runparams.nice) {
1591 // code for usual, NOT nice-latex-file
1592 os << "\\batchmode\n"; // changed from \nonstopmode
1594 if (!original_path.empty()) {
1596 // We don't know the encoding of inputpath
1597 docstring const inputpath = from_utf8(original_path);
1598 docstring uncodable_glyphs;
1599 Encoding const * const enc = runparams.encoding;
1601 for (size_t n = 0; n < inputpath.size(); ++n) {
1602 if (!enc->encodable(inputpath[n])) {
1603 docstring const glyph(1, inputpath[n]);
1604 LYXERR0("Uncodable character '"
1606 << "' in input path!");
1607 uncodable_glyphs += glyph;
1612 // warn user if we found uncodable glyphs.
1613 if (!uncodable_glyphs.empty()) {
1614 frontend::Alert::warning(
1615 _("Uncodable character in file path"),
1617 _("The path of your document\n"
1619 "contains glyphs that are unknown "
1620 "in the current document encoding "
1621 "(namely %2$s). This may result in "
1622 "incomplete output, unless "
1623 "TEXINPUTS contains the document "
1624 "directory and you don't use "
1625 "explicitly relative paths (i.e., "
1626 "paths starting with './' or "
1627 "'../') in the preamble or in ERT."
1628 "\n\nIn case of problems, choose "
1629 "an appropriate document encoding\n"
1630 "(such as utf8) or change the "
1632 inputpath, uncodable_glyphs));
1635 support::latex_path(original_path);
1636 if (contains(docdir, '#')) {
1637 docdir = subst(docdir, "#", "\\#");
1638 os << "\\catcode`\\#=11"
1639 "\\def\\#{#}\\catcode`\\#=6\n";
1641 if (contains(docdir, '%')) {
1642 docdir = subst(docdir, "%", "\\%");
1643 os << "\\catcode`\\%=11"
1644 "\\def\\%{%}\\catcode`\\%=14\n";
1646 os << "\\makeatletter\n"
1647 << "\\def\\input@path{{"
1648 << docdir << "/}}\n"
1649 << "\\makeatother\n";
1653 // get parent macros (if this buffer has a parent) which will be
1654 // written at the document begin further down.
1655 MacroSet parentMacros;
1656 listParentMacros(parentMacros, features);
1658 // Write the preamble
1659 runparams.use_babel = params().writeLaTeX(os, features,
1660 d->filename.onlyPath());
1662 runparams.use_japanese = features.isRequired("japanese");
1665 // Restore the parenthood if needed
1666 if (!runparams.is_child)
1667 d->ignore_parent = false;
1672 os << "\\begin{document}\n";
1674 // output the parent macros
1675 MacroSet::iterator it = parentMacros.begin();
1676 MacroSet::iterator end = parentMacros.end();
1677 for (; it != end; ++it) {
1678 int num_lines = (*it)->write(os.os(), true);
1679 os.texrow().newlines(num_lines);
1682 } // output_preamble
1684 os.texrow().start(paragraphs().begin()->id(), 0);
1686 LYXERR(Debug::INFO, "preamble finished, now the body.");
1689 latexParagraphs(*this, text(), os, runparams);
1691 // Restore the parenthood if needed
1692 if (!runparams.is_child)
1693 d->ignore_parent = false;
1695 // add this just in case after all the paragraphs
1698 if (output_preamble) {
1699 os << "\\end{document}\n";
1700 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1702 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1704 runparams_in.encoding = runparams.encoding;
1706 // Just to be sure. (Asger)
1707 os.texrow().newline();
1709 //for (int i = 0; i<d->texrow.rows(); i++) {
1711 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1712 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1715 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1716 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1720 void Buffer::makeDocBookFile(FileName const & fname,
1721 OutputParams const & runparams,
1722 OutputWhat output) const
1724 LYXERR(Debug::LATEX, "makeDocBookFile...");
1727 if (!openFileWrite(ofs, fname))
1730 // make sure we are ready to export
1731 // this needs to be done before we validate
1733 updateMacroInstances(OutputUpdate);
1735 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1739 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1743 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1744 OutputParams const & runparams,
1745 OutputWhat output) const
1747 LaTeXFeatures features(*this, params(), runparams);
1752 DocumentClass const & tclass = params().documentClass();
1753 string const top_element = tclass.latexname();
1755 bool const output_preamble =
1756 output == FullSource || output == OnlyPreamble;
1757 bool const output_body =
1758 output == FullSource || output == OnlyBody;
1760 if (output_preamble) {
1761 if (runparams.flavor == OutputParams::XML)
1762 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1765 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1768 if (! tclass.class_header().empty())
1769 os << from_ascii(tclass.class_header());
1770 else if (runparams.flavor == OutputParams::XML)
1771 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1772 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1774 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1776 docstring preamble = from_utf8(params().preamble);
1777 if (runparams.flavor != OutputParams::XML ) {
1778 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1779 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1780 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1781 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1784 string const name = runparams.nice
1785 ? changeExtension(absFileName(), ".sgml") : fname;
1786 preamble += features.getIncludedFiles(name);
1787 preamble += features.getLyXSGMLEntities();
1789 if (!preamble.empty()) {
1790 os << "\n [ " << preamble << " ]";
1796 string top = top_element;
1798 if (runparams.flavor == OutputParams::XML)
1799 top += params().language->code();
1801 top += params().language->code().substr(0, 2);
1804 if (!params().options.empty()) {
1806 top += params().options;
1809 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1810 << " file was created by LyX " << lyx_version
1811 << "\n See http://www.lyx.org/ for more information -->\n";
1813 params().documentClass().counters().reset();
1815 sgml::openTag(os, top);
1817 docbookParagraphs(text(), *this, os, runparams);
1818 sgml::closeTag(os, top_element);
1823 void Buffer::makeLyXHTMLFile(FileName const & fname,
1824 OutputParams const & runparams) const
1826 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1829 if (!openFileWrite(ofs, fname))
1832 // make sure we are ready to export
1833 // this has to be done before we validate
1834 updateBuffer(UpdateMaster, OutputUpdate);
1835 updateMacroInstances(OutputUpdate);
1837 writeLyXHTMLSource(ofs, runparams, FullSource);
1841 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1845 void Buffer::writeLyXHTMLSource(odocstream & os,
1846 OutputParams const & runparams,
1847 OutputWhat output) const
1849 LaTeXFeatures features(*this, params(), runparams);
1851 d->bibinfo_.makeCitationLabels(*this);
1853 bool const output_preamble =
1854 output == FullSource || output == OnlyPreamble;
1855 bool const output_body =
1856 output == FullSource || output == OnlyBody || output == IncludedFile;
1858 if (output_preamble) {
1859 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1860 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1861 // FIXME Language should be set properly.
1862 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1864 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1865 // FIXME Presumably need to set this right
1866 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1868 docstring const & doctitle = features.htmlTitle();
1870 << (doctitle.empty() ?
1871 from_ascii("LyX Document") :
1872 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1875 docstring styles = features.getTClassHTMLPreamble();
1876 if (!styles.empty())
1877 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1879 styles = from_utf8(features.getPreambleSnippets());
1880 if (!styles.empty())
1881 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1883 // we will collect CSS information in a stream, and then output it
1884 // either here, as part of the header, or else in a separate file.
1885 odocstringstream css;
1886 styles = from_utf8(features.getCSSSnippets());
1887 if (!styles.empty())
1888 css << "/* LyX Provided Styles */\n" << styles << '\n';
1890 styles = features.getTClassHTMLStyles();
1891 if (!styles.empty())
1892 css << "/* Layout-provided Styles */\n" << styles << '\n';
1894 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1895 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1896 if (needfg || needbg) {
1897 css << "\nbody {\n";
1900 << from_ascii(X11hexname(params().fontcolor))
1903 css << " background-color: "
1904 << from_ascii(X11hexname(params().backgroundcolor))
1909 docstring const dstyles = css.str();
1910 if (!dstyles.empty()) {
1911 bool written = false;
1912 if (params().html_css_as_file) {
1913 // open a file for CSS info
1915 string const fcssname = addName(temppath(), "docstyle.css");
1916 FileName const fcssfile = FileName(fcssname);
1917 if (openFileWrite(ocss, fcssfile)) {
1921 // write link to header
1922 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1924 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1927 // we are here if the CSS is supposed to be written to the header
1928 // or if we failed to write it to an external file.
1930 os << "<style type='text/css'>\n"
1939 bool const output_body_tag = (output != IncludedFile);
1940 if (output_body_tag)
1943 if (output != IncludedFile)
1944 // if we're an included file, the counters are in the master.
1945 params().documentClass().counters().reset();
1946 xhtmlParagraphs(text(), *this, xs, runparams);
1947 if (output_body_tag)
1951 if (output_preamble)
1956 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1957 // Other flags: -wall -v0 -x
1958 int Buffer::runChktex()
1962 // get LaTeX-Filename
1963 FileName const path(temppath());
1964 string const name = addName(path.absFileName(), latexName());
1965 string const org_path = filePath();
1967 PathChanger p(path); // path to LaTeX file
1968 message(_("Running chktex..."));
1970 // Generate the LaTeX file if neccessary
1971 OutputParams runparams(¶ms().encoding());
1972 runparams.flavor = OutputParams::LATEX;
1973 runparams.nice = false;
1974 runparams.linelen = lyxrc.plaintext_linelen;
1975 makeLaTeXFile(FileName(name), org_path, runparams);
1978 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1979 int const res = chktex.run(terr); // run chktex
1982 Alert::error(_("chktex failure"),
1983 _("Could not run chktex successfully."));
1985 ErrorList & errlist = d->errorLists["ChkTeX"];
1987 bufferErrors(terr, errlist);
1998 void Buffer::validate(LaTeXFeatures & features) const
2000 // Validate the buffer params, but not for included
2001 // files, since they also use the parent buffer's
2003 if (!features.runparams().is_child)
2004 params().validate(features);
2006 for_each(paragraphs().begin(), paragraphs().end(),
2007 bind(&Paragraph::validate, _1, ref(features)));
2009 if (lyxerr.debugging(Debug::LATEX)) {
2010 features.showStruct();
2015 void Buffer::getLabelList(vector<docstring> & list) const
2017 // If this is a child document, use the master's list instead.
2019 masterBuffer()->getLabelList(list);
2024 Toc & toc = d->toc_backend.toc("label");
2025 TocIterator toc_it = toc.begin();
2026 TocIterator end = toc.end();
2027 for (; toc_it != end; ++toc_it) {
2028 if (toc_it->depth() == 0)
2029 list.push_back(toc_it->str());
2034 void Buffer::updateBibfilesCache(UpdateScope scope) const
2036 // FIXME This is probably unnecssary, given where we call this.
2037 // If this is a child document, use the parent's cache instead.
2038 if (parent() && scope != UpdateChildOnly) {
2039 masterBuffer()->updateBibfilesCache();
2043 d->bibfiles_cache_.clear();
2044 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2045 if (it->lyxCode() == BIBTEX_CODE) {
2046 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2047 support::FileNameList const bibfiles = inset.getBibFiles();
2048 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2051 } else if (it->lyxCode() == INCLUDE_CODE) {
2052 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2053 Buffer const * const incbuf = inset.getChildBuffer();
2056 support::FileNameList const & bibfiles =
2057 incbuf->getBibfilesCache(UpdateChildOnly);
2058 if (!bibfiles.empty()) {
2059 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2065 d->bibfile_cache_valid_ = true;
2066 d->bibinfo_cache_valid_ = false;
2067 d->cite_labels_valid_ = false;
2071 void Buffer::invalidateBibinfoCache() const
2073 d->bibinfo_cache_valid_ = false;
2074 d->cite_labels_valid_ = false;
2075 // also invalidate the cache for the parent buffer
2076 Buffer const * const pbuf = d->parent();
2078 pbuf->invalidateBibinfoCache();
2082 void Buffer::invalidateBibfileCache() const
2084 d->bibfile_cache_valid_ = false;
2085 d->bibinfo_cache_valid_ = false;
2086 d->cite_labels_valid_ = false;
2087 // also invalidate the cache for the parent buffer
2088 Buffer const * const pbuf = d->parent();
2090 pbuf->invalidateBibfileCache();
2094 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2096 // FIXME This is probably unnecessary, given where we call this.
2097 // If this is a child document, use the master's cache instead.
2098 Buffer const * const pbuf = masterBuffer();
2099 if (pbuf != this && scope != UpdateChildOnly)
2100 return pbuf->getBibfilesCache();
2102 if (!d->bibfile_cache_valid_)
2103 this->updateBibfilesCache(scope);
2105 return d->bibfiles_cache_;
2109 BiblioInfo const & Buffer::masterBibInfo() const
2111 Buffer const * const tmp = masterBuffer();
2113 return tmp->masterBibInfo();
2118 void Buffer::checkIfBibInfoCacheIsValid() const
2120 // use the master's cache
2121 Buffer const * const tmp = masterBuffer();
2123 tmp->checkIfBibInfoCacheIsValid();
2127 // compare the cached timestamps with the actual ones.
2128 FileNameList const & bibfiles_cache = getBibfilesCache();
2129 FileNameList::const_iterator ei = bibfiles_cache.begin();
2130 FileNameList::const_iterator en = bibfiles_cache.end();
2131 for (; ei != en; ++ ei) {
2132 time_t lastw = ei->lastModified();
2133 time_t prevw = d->bibfile_status_[*ei];
2134 if (lastw != prevw) {
2135 d->bibinfo_cache_valid_ = false;
2136 d->cite_labels_valid_ = false;
2137 d->bibfile_status_[*ei] = lastw;
2143 void Buffer::reloadBibInfoCache() const
2145 // use the master's cache
2146 Buffer const * const tmp = masterBuffer();
2148 tmp->reloadBibInfoCache();
2152 checkIfBibInfoCacheIsValid();
2153 if (d->bibinfo_cache_valid_)
2156 d->bibinfo_.clear();
2158 d->bibinfo_cache_valid_ = true;
2162 void Buffer::collectBibKeys() const
2164 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2165 it->collectBibKeys(it);
2169 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2171 Buffer const * tmp = masterBuffer();
2172 BiblioInfo & masterbi = (tmp == this) ?
2173 d->bibinfo_ : tmp->d->bibinfo_;
2174 masterbi.mergeBiblioInfo(bi);
2178 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2180 Buffer const * tmp = masterBuffer();
2181 BiblioInfo & masterbi = (tmp == this) ?
2182 d->bibinfo_ : tmp->d->bibinfo_;
2187 void Buffer::makeCitationLabels() const
2189 Buffer const * const master = masterBuffer();
2190 return d->bibinfo_.makeCitationLabels(*master);
2194 bool Buffer::citeLabelsValid() const
2196 return masterBuffer()->d->cite_labels_valid_;
2200 void Buffer::removeBiblioTempFiles() const
2202 // We remove files that contain LaTeX commands specific to the
2203 // particular bibliographic style being used, in order to avoid
2204 // LaTeX errors when we switch style.
2205 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2206 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2207 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2208 aux_file.removeFile();
2209 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2210 bbl_file.removeFile();
2211 // Also for the parent buffer
2212 Buffer const * const pbuf = parent();
2214 pbuf->removeBiblioTempFiles();
2218 bool Buffer::isDepClean(string const & name) const
2220 DepClean::const_iterator const it = d->dep_clean.find(name);
2221 if (it == d->dep_clean.end())
2227 void Buffer::markDepClean(string const & name)
2229 d->dep_clean[name] = true;
2233 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2236 // FIXME? if there is an Buffer LFUN that can be dispatched even
2237 // if internal, put a switch '(cmd.action)' here.
2243 switch (cmd.action()) {
2245 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2246 flag.setOnOff(isReadonly());
2249 // FIXME: There is need for a command-line import.
2250 //case LFUN_BUFFER_IMPORT:
2252 case LFUN_BUFFER_AUTO_SAVE:
2255 case LFUN_BUFFER_EXPORT_CUSTOM:
2256 // FIXME: Nothing to check here?
2259 case LFUN_BUFFER_EXPORT: {
2260 docstring const arg = cmd.argument();
2261 if (arg == "custom") {
2265 string format = to_utf8(arg);
2266 size_t pos = format.find(' ');
2267 if (pos != string::npos)
2268 format = format.substr(0, pos);
2269 enable = params().isExportable(format);
2271 flag.message(bformat(
2272 _("Don't know how to export to format: %1$s"), arg));
2276 case LFUN_BUFFER_CHKTEX:
2277 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2280 case LFUN_BUILD_PROGRAM:
2281 enable = params().isExportable("program");
2284 case LFUN_BRANCH_ADD:
2285 case LFUN_BRANCHES_RENAME:
2286 case LFUN_BUFFER_PRINT:
2287 // if no Buffer is present, then of course we won't be called!
2290 case LFUN_BUFFER_LANGUAGE:
2291 enable = !isReadonly();
2297 flag.setEnabled(enable);
2302 void Buffer::dispatch(string const & command, DispatchResult & result)
2304 return dispatch(lyxaction.lookupFunc(command), result);
2308 // NOTE We can end up here even if we have no GUI, because we are called
2309 // by LyX::exec to handled command-line requests. So we may need to check
2310 // whether we have a GUI or not. The boolean use_gui holds this information.
2311 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2314 // FIXME? if there is an Buffer LFUN that can be dispatched even
2315 // if internal, put a switch '(cmd.action())' here.
2316 dr.dispatched(false);
2319 string const argument = to_utf8(func.argument());
2320 // We'll set this back to false if need be.
2321 bool dispatched = true;
2322 undo().beginUndoGroup();
2324 switch (func.action()) {
2325 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2326 if (lyxvc().inUse()) {
2327 string log = lyxvc().toggleReadOnly();
2332 setReadonly(!isReadonly());
2335 case LFUN_BUFFER_EXPORT: {
2336 ExportStatus const status = doExport(argument, false);
2337 dr.setError(status != ExportSuccess);
2338 if (status != ExportSuccess)
2339 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2344 case LFUN_BUILD_PROGRAM:
2345 doExport("program", true);
2348 case LFUN_BUFFER_CHKTEX:
2352 case LFUN_BUFFER_EXPORT_CUSTOM: {
2354 string command = split(argument, format_name, ' ');
2355 Format const * format = formats.getFormat(format_name);
2357 lyxerr << "Format \"" << format_name
2358 << "\" not recognized!"
2363 // The name of the file created by the conversion process
2366 // Output to filename
2367 if (format->name() == "lyx") {
2368 string const latexname = latexName(false);
2369 filename = changeExtension(latexname,
2370 format->extension());
2371 filename = addName(temppath(), filename);
2373 if (!writeFile(FileName(filename)))
2377 doExport(format_name, true, filename);
2380 // Substitute $$FName for filename
2381 if (!contains(command, "$$FName"))
2382 command = "( " + command + " ) < $$FName";
2383 command = subst(command, "$$FName", filename);
2385 // Execute the command in the background
2387 call.startscript(Systemcall::DontWait, command, filePath());
2391 // FIXME: There is need for a command-line import.
2393 case LFUN_BUFFER_IMPORT:
2398 case LFUN_BUFFER_AUTO_SAVE:
2400 resetAutosaveTimers();
2403 case LFUN_BRANCH_ADD: {
2404 docstring branch_name = func.argument();
2405 if (branch_name.empty()) {
2409 BranchList & branch_list = params().branchlist();
2410 vector<docstring> const branches =
2411 getVectorFromString(branch_name, branch_list.separator());
2413 for (vector<docstring>::const_iterator it = branches.begin();
2414 it != branches.end(); ++it) {
2416 Branch * branch = branch_list.find(branch_name);
2418 LYXERR0("Branch " << branch_name << " already exists.");
2422 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2424 branch_list.add(branch_name);
2425 branch = branch_list.find(branch_name);
2426 string const x11hexname = X11hexname(branch->color());
2427 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2428 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2430 dr.screenUpdate(Update::Force);
2438 case LFUN_BRANCHES_RENAME: {
2439 if (func.argument().empty())
2442 docstring const oldname = from_utf8(func.getArg(0));
2443 docstring const newname = from_utf8(func.getArg(1));
2444 InsetIterator it = inset_iterator_begin(inset());
2445 InsetIterator const end = inset_iterator_end(inset());
2446 bool success = false;
2447 for (; it != end; ++it) {
2448 if (it->lyxCode() == BRANCH_CODE) {
2449 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2450 if (ins.branch() == oldname) {
2451 undo().recordUndo(CursorData(it));
2452 ins.rename(newname);
2457 if (it->lyxCode() == INCLUDE_CODE) {
2458 // get buffer of external file
2459 InsetInclude const & ins =
2460 static_cast<InsetInclude const &>(*it);
2461 Buffer * child = ins.getChildBuffer();
2464 child->dispatch(func, dr);
2469 dr.screenUpdate(Update::Force);
2470 dr.forceBufferUpdate();
2475 case LFUN_BUFFER_PRINT: {
2476 // we'll assume there's a problem until we succeed
2478 string target = func.getArg(0);
2479 string target_name = func.getArg(1);
2480 string command = func.getArg(2);
2483 || target_name.empty()
2484 || command.empty()) {
2485 LYXERR0("Unable to parse " << func.argument());
2486 docstring const msg =
2487 bformat(_("Unable to parse \"%1$s\""), func.argument());
2491 if (target != "printer" && target != "file") {
2492 LYXERR0("Unrecognized target \"" << target << '"');
2493 docstring const msg =
2494 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2499 if (!doExport("dvi", true)) {
2500 showPrintError(absFileName());
2501 dr.setMessage(_("Error exporting to DVI."));
2505 // Push directory path.
2506 string const path = temppath();
2507 // Prevent the compiler from optimizing away p
2511 // there are three cases here:
2512 // 1. we print to a file
2513 // 2. we print directly to a printer
2514 // 3. we print using a spool command (print to file first)
2517 string const dviname = changeExtension(latexName(true), "dvi");
2519 if (target == "printer") {
2520 if (!lyxrc.print_spool_command.empty()) {
2521 // case 3: print using a spool
2522 string const psname = changeExtension(dviname,".ps");
2523 command += ' ' + lyxrc.print_to_file
2526 + quoteName(dviname);
2528 string command2 = lyxrc.print_spool_command + ' ';
2529 if (target_name != "default") {
2530 command2 += lyxrc.print_spool_printerprefix
2534 command2 += quoteName(psname);
2536 // If successful, then spool command
2537 res = one.startscript(Systemcall::Wait, command,
2541 // If there's no GUI, we have to wait on this command. Otherwise,
2542 // LyX deletes the temporary directory, and with it the spooled
2543 // file, before it can be printed!!
2544 Systemcall::Starttype stype = use_gui ?
2545 Systemcall::DontWait : Systemcall::Wait;
2546 res = one.startscript(stype, command2,
2550 // case 2: print directly to a printer
2551 if (target_name != "default")
2552 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2554 Systemcall::Starttype stype = use_gui ?
2555 Systemcall::DontWait : Systemcall::Wait;
2556 res = one.startscript(stype, command +
2557 quoteName(dviname), filePath());
2561 // case 1: print to a file
2562 FileName const filename(makeAbsPath(target_name, filePath()));
2563 FileName const dvifile(makeAbsPath(dviname, path));
2564 if (filename.exists()) {
2565 docstring text = bformat(
2566 _("The file %1$s already exists.\n\n"
2567 "Do you want to overwrite that file?"),
2568 makeDisplayPath(filename.absFileName()));
2569 if (Alert::prompt(_("Overwrite file?"),
2570 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2573 command += ' ' + lyxrc.print_to_file
2574 + quoteName(filename.toFilesystemEncoding())
2576 + quoteName(dvifile.toFilesystemEncoding());
2578 Systemcall::Starttype stype = use_gui ?
2579 Systemcall::DontWait : Systemcall::Wait;
2580 res = one.startscript(stype, command, filePath());
2586 dr.setMessage(_("Error running external commands."));
2587 showPrintError(absFileName());
2596 dr.dispatched(dispatched);
2597 undo().endUndoGroup();
2601 void Buffer::changeLanguage(Language const * from, Language const * to)
2603 LASSERT(from, /**/);
2606 for_each(par_iterator_begin(),
2608 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2612 bool Buffer::isMultiLingual() const
2614 ParConstIterator end = par_iterator_end();
2615 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2616 if (it->isMultiLingual(params()))
2623 std::set<Language const *> Buffer::getLanguages() const
2625 std::set<Language const *> languages;
2626 getLanguages(languages);
2631 void Buffer::getLanguages(std::set<Language const *> & languages) const
2633 ParConstIterator end = par_iterator_end();
2634 // add the buffer language, even if it's not actively used
2635 languages.insert(language());
2636 // iterate over the paragraphs
2637 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2638 it->getLanguages(languages);
2640 ListOfBuffers clist = getDescendents();
2641 ListOfBuffers::const_iterator cit = clist.begin();
2642 ListOfBuffers::const_iterator const cen = clist.end();
2643 for (; cit != cen; ++cit)
2644 (*cit)->getLanguages(languages);
2648 DocIterator Buffer::getParFromID(int const id) const
2650 Buffer * buf = const_cast<Buffer *>(this);
2652 // John says this is called with id == -1 from undo
2653 lyxerr << "getParFromID(), id: " << id << endl;
2654 return doc_iterator_end(buf);
2657 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2658 if (it.paragraph().id() == id)
2661 return doc_iterator_end(buf);
2665 bool Buffer::hasParWithID(int const id) const
2667 return !getParFromID(id).atEnd();
2671 ParIterator Buffer::par_iterator_begin()
2673 return ParIterator(doc_iterator_begin(this));
2677 ParIterator Buffer::par_iterator_end()
2679 return ParIterator(doc_iterator_end(this));
2683 ParConstIterator Buffer::par_iterator_begin() const
2685 return ParConstIterator(doc_iterator_begin(this));
2689 ParConstIterator Buffer::par_iterator_end() const
2691 return ParConstIterator(doc_iterator_end(this));
2695 Language const * Buffer::language() const
2697 return params().language;
2701 docstring const Buffer::B_(string const & l10n) const
2703 return params().B_(l10n);
2707 bool Buffer::isClean() const
2709 return d->lyx_clean;
2713 bool Buffer::isExternallyModified(CheckMethod method) const
2715 LASSERT(d->filename.exists(), /**/);
2716 // if method == timestamp, check timestamp before checksum
2717 return (method == checksum_method
2718 || d->timestamp_ != d->filename.lastModified())
2719 && d->checksum_ != d->filename.checksum();
2723 void Buffer::saveCheckSum() const
2725 FileName const & file = d->filename;
2728 if (file.exists()) {
2729 d->timestamp_ = file.lastModified();
2730 d->checksum_ = file.checksum();
2732 // in the case of save to a new file.
2739 void Buffer::markClean() const
2741 if (!d->lyx_clean) {
2742 d->lyx_clean = true;
2745 // if the .lyx file has been saved, we don't need an
2747 d->bak_clean = true;
2748 d->undo_.markDirty();
2752 void Buffer::setUnnamed(bool flag)
2758 bool Buffer::isUnnamed() const
2765 /// Don't check unnamed, here: isInternal() is used in
2766 /// newBuffer(), where the unnamed flag has not been set by anyone
2767 /// yet. Also, for an internal buffer, there should be no need for
2768 /// retrieving fileName() nor for checking if it is unnamed or not.
2769 bool Buffer::isInternal() const
2771 return d->internal_buffer;
2775 void Buffer::setInternal(bool flag)
2777 d->internal_buffer = flag;
2781 void Buffer::markDirty()
2784 d->lyx_clean = false;
2787 d->bak_clean = false;
2789 DepClean::iterator it = d->dep_clean.begin();
2790 DepClean::const_iterator const end = d->dep_clean.end();
2792 for (; it != end; ++it)
2797 FileName Buffer::fileName() const
2803 string Buffer::absFileName() const
2805 return d->filename.absFileName();
2809 string Buffer::filePath() const
2811 string const abs = d->filename.onlyPath().absFileName();
2814 int last = abs.length() - 1;
2816 return abs[last] == '/' ? abs : abs + '/';
2820 bool Buffer::isReadonly() const
2822 return d->read_only;
2826 void Buffer::setParent(Buffer const * buffer)
2828 // Avoids recursive include.
2829 d->setParent(buffer == this ? 0 : buffer);
2834 Buffer const * Buffer::parent() const
2840 ListOfBuffers Buffer::allRelatives() const
2842 ListOfBuffers lb = masterBuffer()->getDescendents();
2843 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2848 Buffer const * Buffer::masterBuffer() const
2850 // FIXME Should be make sure we are not in some kind
2851 // of recursive include? A -> B -> A will crash this.
2852 Buffer const * const pbuf = d->parent();
2856 return pbuf->masterBuffer();
2860 bool Buffer::isChild(Buffer * child) const
2862 return d->children_positions.find(child) != d->children_positions.end();
2866 DocIterator Buffer::firstChildPosition(Buffer const * child)
2868 Impl::BufferPositionMap::iterator it;
2869 it = d->children_positions.find(child);
2870 if (it == d->children_positions.end())
2871 return DocIterator(this);
2876 bool Buffer::hasChildren() const
2878 return !d->children_positions.empty();
2882 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2884 // loop over children
2885 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2886 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2887 for (; it != end; ++it) {
2888 Buffer * child = const_cast<Buffer *>(it->first);
2890 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2891 if (bit != clist.end())
2893 clist.push_back(child);
2895 // there might be grandchildren
2896 child->collectChildren(clist, true);
2901 ListOfBuffers Buffer::getChildren() const
2904 collectChildren(v, false);
2905 // Make sure we have not included ourselves.
2906 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2907 if (bit != v.end()) {
2908 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2915 ListOfBuffers Buffer::getDescendents() const
2918 collectChildren(v, true);
2919 // Make sure we have not included ourselves.
2920 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2921 if (bit != v.end()) {
2922 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2929 template<typename M>
2930 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2935 typename M::const_iterator it = m.lower_bound(x);
2936 if (it == m.begin())
2944 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2945 DocIterator const & pos) const
2947 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2949 // if paragraphs have no macro context set, pos will be empty
2953 // we haven't found anything yet
2954 DocIterator bestPos = owner_->par_iterator_begin();
2955 MacroData const * bestData = 0;
2957 // find macro definitions for name
2958 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2959 if (nameIt != macros.end()) {
2960 // find last definition in front of pos or at pos itself
2961 PositionScopeMacroMap::const_iterator it
2962 = greatest_below(nameIt->second, pos);
2963 if (it != nameIt->second.end()) {
2965 // scope ends behind pos?
2966 if (pos < it->second.first) {
2967 // Looks good, remember this. If there
2968 // is no external macro behind this,
2969 // we found the right one already.
2970 bestPos = it->first;
2971 bestData = &it->second.second;
2975 // try previous macro if there is one
2976 if (it == nameIt->second.begin())
2983 // find macros in included files
2984 PositionScopeBufferMap::const_iterator it
2985 = greatest_below(position_to_children, pos);
2986 if (it == position_to_children.end())
2987 // no children before
2991 // do we know something better (i.e. later) already?
2992 if (it->first < bestPos )
2995 // scope ends behind pos?
2996 if (pos < it->second.first
2997 && (cloned_buffer_ ||
2998 theBufferList().isLoaded(it->second.second))) {
2999 // look for macro in external file
3001 MacroData const * data
3002 = it->second.second->getMacro(name, false);
3005 bestPos = it->first;
3011 // try previous file if there is one
3012 if (it == position_to_children.begin())
3017 // return the best macro we have found
3022 MacroData const * Buffer::getMacro(docstring const & name,
3023 DocIterator const & pos, bool global) const
3028 // query buffer macros
3029 MacroData const * data = d->getBufferMacro(name, pos);
3033 // If there is a master buffer, query that
3034 Buffer const * const pbuf = d->parent();
3036 d->macro_lock = true;
3037 MacroData const * macro = pbuf->getMacro(
3038 name, *this, false);
3039 d->macro_lock = false;
3045 data = MacroTable::globalMacros().get(name);
3054 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3056 // set scope end behind the last paragraph
3057 DocIterator scope = par_iterator_begin();
3058 scope.pit() = scope.lastpit() + 1;
3060 return getMacro(name, scope, global);
3064 MacroData const * Buffer::getMacro(docstring const & name,
3065 Buffer const & child, bool global) const
3067 // look where the child buffer is included first
3068 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3069 if (it == d->children_positions.end())
3072 // check for macros at the inclusion position
3073 return getMacro(name, it->second, global);
3077 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3079 pit_type const lastpit = it.lastpit();
3081 // look for macros in each paragraph
3082 while (it.pit() <= lastpit) {
3083 Paragraph & par = it.paragraph();
3085 // iterate over the insets of the current paragraph
3086 InsetList const & insets = par.insetList();
3087 InsetList::const_iterator iit = insets.begin();
3088 InsetList::const_iterator end = insets.end();
3089 for (; iit != end; ++iit) {
3090 it.pos() = iit->pos;
3092 // is it a nested text inset?
3093 if (iit->inset->asInsetText()) {
3094 // Inset needs its own scope?
3095 InsetText const * itext = iit->inset->asInsetText();
3096 bool newScope = itext->isMacroScope();
3098 // scope which ends just behind the inset
3099 DocIterator insetScope = it;
3102 // collect macros in inset
3103 it.push_back(CursorSlice(*iit->inset));
3104 updateMacros(it, newScope ? insetScope : scope);
3109 if (iit->inset->asInsetTabular()) {
3110 CursorSlice slice(*iit->inset);
3111 size_t const numcells = slice.nargs();
3112 for (; slice.idx() < numcells; slice.forwardIdx()) {
3113 it.push_back(slice);
3114 updateMacros(it, scope);
3120 // is it an external file?
3121 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3122 // get buffer of external file
3123 InsetInclude const & inset =
3124 static_cast<InsetInclude const &>(*iit->inset);
3126 Buffer * child = inset.getChildBuffer();
3131 // register its position, but only when it is
3132 // included first in the buffer
3133 if (children_positions.find(child) ==
3134 children_positions.end())
3135 children_positions[child] = it;
3137 // register child with its scope
3138 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3142 InsetMath * im = iit->inset->asInsetMath();
3143 if (doing_export && im) {
3144 InsetMathHull * hull = im->asHullInset();
3146 hull->recordLocation(it);
3149 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3153 MathMacroTemplate & macroTemplate =
3154 *iit->inset->asInsetMath()->asMacroTemplate();
3155 MacroContext mc(owner_, it);
3156 macroTemplate.updateToContext(mc);
3159 bool valid = macroTemplate.validMacro();
3160 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3161 // then the BufferView's cursor will be invalid in
3162 // some cases which leads to crashes.
3167 // FIXME (Abdel), I don't understandt why we pass 'it' here
3168 // instead of 'macroTemplate' defined above... is this correct?
3169 macros[macroTemplate.name()][it] =
3170 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3180 void Buffer::updateMacros() const
3185 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3187 // start with empty table
3189 d->children_positions.clear();
3190 d->position_to_children.clear();
3192 // Iterate over buffer, starting with first paragraph
3193 // The scope must be bigger than any lookup DocIterator
3194 // later. For the global lookup, lastpit+1 is used, hence
3195 // we use lastpit+2 here.
3196 DocIterator it = par_iterator_begin();
3197 DocIterator outerScope = it;
3198 outerScope.pit() = outerScope.lastpit() + 2;
3199 d->updateMacros(it, outerScope);
3203 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3205 InsetIterator it = inset_iterator_begin(inset());
3206 InsetIterator const end = inset_iterator_end(inset());
3207 for (; it != end; ++it) {
3208 if (it->lyxCode() == BRANCH_CODE) {
3209 InsetBranch & br = static_cast<InsetBranch &>(*it);
3210 docstring const name = br.branch();
3211 if (!from_master && !params().branchlist().find(name))
3212 result.push_back(name);
3213 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3214 result.push_back(name);
3217 if (it->lyxCode() == INCLUDE_CODE) {
3218 // get buffer of external file
3219 InsetInclude const & ins =
3220 static_cast<InsetInclude const &>(*it);
3221 Buffer * child = ins.getChildBuffer();
3224 child->getUsedBranches(result, true);
3227 // remove duplicates
3232 void Buffer::updateMacroInstances(UpdateType utype) const
3234 LYXERR(Debug::MACROS, "updateMacroInstances for "
3235 << d->filename.onlyFileName());
3236 DocIterator it = doc_iterator_begin(this);
3238 DocIterator const end = doc_iterator_end(this);
3239 for (; it != end; it.forwardInset()) {
3240 // look for MathData cells in InsetMathNest insets
3241 InsetMath * minset = it.nextInset()->asInsetMath();
3245 // update macro in all cells of the InsetMathNest
3246 DocIterator::idx_type n = minset->nargs();
3247 MacroContext mc = MacroContext(this, it);
3248 for (DocIterator::idx_type i = 0; i < n; ++i) {
3249 MathData & data = minset->cell(i);
3250 data.updateMacros(0, mc, utype);
3256 void Buffer::listMacroNames(MacroNameSet & macros) const
3261 d->macro_lock = true;
3263 // loop over macro names
3264 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3265 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3266 for (; nameIt != nameEnd; ++nameIt)
3267 macros.insert(nameIt->first);
3269 // loop over children
3270 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3271 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3272 for (; it != end; ++it)
3273 it->first->listMacroNames(macros);
3276 Buffer const * const pbuf = d->parent();
3278 pbuf->listMacroNames(macros);
3280 d->macro_lock = false;
3284 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3286 Buffer const * const pbuf = d->parent();
3291 pbuf->listMacroNames(names);
3294 MacroNameSet::iterator it = names.begin();
3295 MacroNameSet::iterator end = names.end();
3296 for (; it != end; ++it) {
3298 MacroData const * data =
3299 pbuf->getMacro(*it, *this, false);
3301 macros.insert(data);
3303 // we cannot access the original MathMacroTemplate anymore
3304 // here to calls validate method. So we do its work here manually.
3305 // FIXME: somehow make the template accessible here.
3306 if (data->optionals() > 0)
3307 features.require("xargs");
3313 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3316 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3318 RefCache::iterator it = d->ref_cache_.find(label);
3319 if (it != d->ref_cache_.end())
3320 return it->second.second;
3322 static InsetLabel const * dummy_il = 0;
3323 static References const dummy_refs;
3324 it = d->ref_cache_.insert(
3325 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3326 return it->second.second;
3330 Buffer::References const & Buffer::references(docstring const & label) const
3332 return const_cast<Buffer *>(this)->getReferenceCache(label);
3336 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3338 References & refs = getReferenceCache(label);
3339 refs.push_back(make_pair(inset, it));
3343 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3345 masterBuffer()->d->ref_cache_[label].first = il;
3349 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3351 return masterBuffer()->d->ref_cache_[label].first;
3355 void Buffer::clearReferenceCache() const
3358 d->ref_cache_.clear();
3362 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3364 //FIXME: This does not work for child documents yet.
3365 reloadBibInfoCache();
3367 // Check if the label 'from' appears more than once
3368 BiblioInfo const & keys = masterBibInfo();
3369 BiblioInfo::const_iterator bit = keys.begin();
3370 BiblioInfo::const_iterator bend = keys.end();
3371 vector<docstring> labels;
3373 for (; bit != bend; ++bit)
3375 labels.push_back(bit->first);
3377 if (count(labels.begin(), labels.end(), from) > 1)
3380 string const paramName = "key";
3381 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3382 if (it->lyxCode() != CITE_CODE)
3384 InsetCommand * inset = it->asInsetCommand();
3385 docstring const oldValue = inset->getParam(paramName);
3386 if (oldValue == from)
3387 inset->setParam(paramName, to);
3392 void Buffer::getSourceCode(odocstream & os, string const format,
3393 pit_type par_begin, pit_type par_end,
3394 OutputWhat output, bool master) const
3396 OutputParams runparams(¶ms().encoding());
3397 runparams.nice = true;
3398 runparams.flavor = params().getOutputFlavor(format);
3399 runparams.linelen = lyxrc.plaintext_linelen;
3400 // No side effect of file copying and image conversion
3401 runparams.dryrun = true;
3403 if (output == CurrentParagraph) {
3404 runparams.par_begin = par_begin;
3405 runparams.par_end = par_end;
3406 if (par_begin + 1 == par_end) {
3408 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3412 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3413 convert<docstring>(par_begin),
3414 convert<docstring>(par_end - 1))
3417 // output paragraphs
3418 if (runparams.flavor == OutputParams::LYX) {
3419 Paragraph const & par = text().paragraphs()[par_begin];
3421 depth_type dt = par.getDepth();
3422 par.write(ods, params(), dt);
3423 os << from_utf8(ods.str());
3424 } else if (runparams.flavor == OutputParams::HTML) {
3426 setMathFlavor(runparams);
3427 xhtmlParagraphs(text(), *this, xs, runparams);
3428 } else if (runparams.flavor == OutputParams::TEXT) {
3430 // FIXME Handles only one paragraph, unlike the others.
3431 // Probably should have some routine with a signature like them.
3432 writePlaintextParagraph(*this,
3433 text().paragraphs()[par_begin], os, runparams, dummy);
3434 } else if (params().isDocBook()) {
3435 docbookParagraphs(text(), *this, os, runparams);
3437 // If we are previewing a paragraph, even if this is the
3438 // child of some other buffer, let's cut the link here,
3439 // so that no concurring settings from the master
3440 // (e.g. branch state) interfere (see #8101).
3442 d->ignore_parent = true;
3443 // We need to validate the Buffer params' features here
3444 // in order to know if we should output polyglossia
3445 // macros (instead of babel macros)
3446 LaTeXFeatures features(*this, params(), runparams);
3447 params().validate(features);
3448 runparams.use_polyglossia = features.usePolyglossia();
3453 // latex or literate
3454 otexstream ots(os, texrow);
3457 latexParagraphs(*this, text(), ots, runparams);
3459 // Restore the parenthood
3461 d->ignore_parent = false;
3465 if (output == FullSource)
3466 os << _("Preview source code");
3467 else if (output == OnlyPreamble)
3468 os << _("Preview preamble");
3469 else if (output == OnlyBody)
3470 os << _("Preview body");
3472 if (runparams.flavor == OutputParams::LYX) {
3474 if (output == FullSource)
3476 else if (output == OnlyPreamble)
3477 params().writeFile(ods);
3478 else if (output == OnlyBody)
3480 os << from_utf8(ods.str());
3481 } else if (runparams.flavor == OutputParams::HTML) {
3482 writeLyXHTMLSource(os, runparams, output);
3483 } else if (runparams.flavor == OutputParams::TEXT) {
3484 if (output == OnlyPreamble) {
3485 os << "% "<< _("Plain text does not have a preamble.");
3487 writePlaintextFile(*this, os, runparams);
3488 } else if (params().isDocBook()) {
3489 writeDocBookSource(os, absFileName(), runparams, output);
3491 // latex or literate
3493 d->texrow.newline();
3494 d->texrow.newline();
3495 otexstream ots(os, d->texrow);
3497 runparams.is_child = true;
3498 writeLaTeXSource(ots, string(), runparams, output);
3504 ErrorList & Buffer::errorList(string const & type) const
3506 return d->errorLists[type];
3510 void Buffer::updateTocItem(std::string const & type,
3511 DocIterator const & dit) const
3514 d->gui_->updateTocItem(type, dit);
3518 void Buffer::structureChanged() const
3521 d->gui_->structureChanged();
3525 void Buffer::errors(string const & err, bool from_master) const
3528 d->gui_->errors(err, from_master);
3532 void Buffer::message(docstring const & msg) const
3535 d->gui_->message(msg);
3539 void Buffer::setBusy(bool on) const
3542 d->gui_->setBusy(on);
3546 void Buffer::updateTitles() const
3549 d->wa_->updateTitles();
3553 void Buffer::resetAutosaveTimers() const
3556 d->gui_->resetAutosaveTimers();
3560 bool Buffer::hasGuiDelegate() const
3566 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3575 class AutoSaveBuffer : public ForkedProcess {
3578 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3579 : buffer_(buffer), fname_(fname) {}
3581 virtual shared_ptr<ForkedProcess> clone() const
3583 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3588 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3589 from_utf8(fname_.absFileName())));
3590 return run(DontWait);
3594 virtual int generateChild();
3596 Buffer const & buffer_;
3601 int AutoSaveBuffer::generateChild()
3603 #if defined(__APPLE__)
3604 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3605 * We should use something else like threads.
3607 * Since I do not know how to determine at run time what is the OS X
3608 * version, I just disable forking altogether for now (JMarc)
3610 pid_t const pid = -1;
3612 // tmp_ret will be located (usually) in /tmp
3613 // will that be a problem?
3614 // Note that this calls ForkedCalls::fork(), so it's
3615 // ok cross-platform.
3616 pid_t const pid = fork();
3617 // If you want to debug the autosave
3618 // you should set pid to -1, and comment out the fork.
3619 if (pid != 0 && pid != -1)
3623 // pid = -1 signifies that lyx was unable
3624 // to fork. But we will do the save
3626 bool failed = false;
3627 FileName const tmp_ret = FileName::tempName("lyxauto");
3628 if (!tmp_ret.empty()) {
3629 buffer_.writeFile(tmp_ret);
3630 // assume successful write of tmp_ret
3631 if (!tmp_ret.moveTo(fname_))
3637 // failed to write/rename tmp_ret so try writing direct
3638 if (!buffer_.writeFile(fname_)) {
3639 // It is dangerous to do this in the child,
3640 // but safe in the parent, so...
3641 if (pid == -1) // emit message signal.
3642 buffer_.message(_("Autosave failed!"));
3646 if (pid == 0) // we are the child so...
3655 FileName Buffer::getEmergencyFileName() const
3657 return FileName(d->filename.absFileName() + ".emergency");
3661 FileName Buffer::getAutosaveFileName() const
3663 // if the document is unnamed try to save in the backup dir, else
3664 // in the default document path, and as a last try in the filePath,
3665 // which will most often be the temporary directory
3668 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3669 : lyxrc.backupdir_path;
3670 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3673 string const fname = "#" + d->filename.onlyFileName() + "#";
3675 return makeAbsPath(fname, fpath);
3679 void Buffer::removeAutosaveFile() const
3681 FileName const f = getAutosaveFileName();
3687 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3689 FileName const newauto = getAutosaveFileName();
3691 if (newauto != oldauto && oldauto.exists())
3692 if (!oldauto.moveTo(newauto))
3693 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3697 bool Buffer::autoSave() const
3699 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3700 if (buf->d->bak_clean || isReadonly())
3703 message(_("Autosaving current document..."));
3704 buf->d->bak_clean = true;
3706 FileName const fname = getAutosaveFileName();
3707 LASSERT(d->cloned_buffer_, return false);
3709 // If this buffer is cloned, we assume that
3710 // we are running in a separate thread already.
3711 FileName const tmp_ret = FileName::tempName("lyxauto");
3712 if (!tmp_ret.empty()) {
3714 // assume successful write of tmp_ret
3715 if (tmp_ret.moveTo(fname))
3718 // failed to write/rename tmp_ret so try writing direct
3719 return writeFile(fname);
3723 void Buffer::setExportStatus(bool e) const
3725 d->doing_export = e;
3726 ListOfBuffers clist = getDescendents();
3727 ListOfBuffers::const_iterator cit = clist.begin();
3728 ListOfBuffers::const_iterator const cen = clist.end();
3729 for (; cit != cen; ++cit)
3730 (*cit)->d->doing_export = e;
3734 bool Buffer::isExporting() const
3736 return d->doing_export;
3740 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3744 return doExport(target, put_in_tempdir, result_file);
3747 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3748 string & result_file) const
3750 bool const update_unincluded =
3751 params().maintain_unincluded_children
3752 && !params().getIncludedChildren().empty();
3754 // (1) export with all included children (omit \includeonly)
3755 if (update_unincluded) {
3756 ExportStatus const status =
3757 doExport(target, put_in_tempdir, true, result_file);
3758 if (status != ExportSuccess)
3761 // (2) export with included children only
3762 return doExport(target, put_in_tempdir, false, result_file);
3766 void Buffer::setMathFlavor(OutputParams & op) const
3768 switch (params().html_math_output) {
3769 case BufferParams::MathML:
3770 op.math_flavor = OutputParams::MathAsMathML;
3772 case BufferParams::HTML:
3773 op.math_flavor = OutputParams::MathAsHTML;
3775 case BufferParams::Images:
3776 op.math_flavor = OutputParams::MathAsImages;
3778 case BufferParams::LaTeX:
3779 op.math_flavor = OutputParams::MathAsLaTeX;
3785 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3786 bool includeall, string & result_file) const
3788 LYXERR(Debug::FILES, "target=" << target);
3789 OutputParams runparams(¶ms().encoding());
3790 string format = target;
3791 string dest_filename;
3792 size_t pos = target.find(' ');
3793 if (pos != string::npos) {
3794 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3795 format = target.substr(0, pos);
3796 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3797 FileName(dest_filename).onlyPath().createPath();
3798 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3800 MarkAsExporting exporting(this);
3801 string backend_format;
3802 runparams.flavor = OutputParams::LATEX;
3803 runparams.linelen = lyxrc.plaintext_linelen;
3804 runparams.includeall = includeall;
3805 vector<string> backs = params().backends();
3806 Converters converters = theConverters();
3807 bool need_nice_file = false;
3808 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3809 // Get shortest path to format
3810 converters.buildGraph();
3811 Graph::EdgePath path;
3812 for (vector<string>::const_iterator it = backs.begin();
3813 it != backs.end(); ++it) {
3814 Graph::EdgePath p = converters.getPath(*it, format);
3815 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3816 backend_format = *it;
3821 if (!put_in_tempdir) {
3822 // Only show this alert if this is an export to a non-temporary
3823 // file (not for previewing).
3824 Alert::error(_("Couldn't export file"), bformat(
3825 _("No information for exporting the format %1$s."),
3826 formats.prettyName(format)));
3828 return ExportNoPathToFormat;
3830 runparams.flavor = converters.getFlavor(path, this);
3831 Graph::EdgePath::const_iterator it = path.begin();
3832 Graph::EdgePath::const_iterator en = path.end();
3833 for (; it != en; ++it)
3834 if (theConverters().get(*it).nice) {
3835 need_nice_file = true;
3840 backend_format = format;
3841 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3842 // FIXME: Don't hardcode format names here, but use a flag
3843 if (backend_format == "pdflatex")
3844 runparams.flavor = OutputParams::PDFLATEX;
3845 else if (backend_format == "luatex")
3846 runparams.flavor = OutputParams::LUATEX;
3847 else if (backend_format == "dviluatex")
3848 runparams.flavor = OutputParams::DVILUATEX;
3849 else if (backend_format == "xetex")
3850 runparams.flavor = OutputParams::XETEX;
3853 string filename = latexName(false);
3854 filename = addName(temppath(), filename);
3855 filename = changeExtension(filename,
3856 formats.extension(backend_format));
3857 LYXERR(Debug::FILES, "filename=" << filename);
3859 // Plain text backend
3860 if (backend_format == "text") {
3861 runparams.flavor = OutputParams::TEXT;
3862 writePlaintextFile(*this, FileName(filename), runparams);
3865 else if (backend_format == "xhtml") {
3866 runparams.flavor = OutputParams::HTML;
3867 setMathFlavor(runparams);
3868 makeLyXHTMLFile(FileName(filename), runparams);
3869 } else if (backend_format == "lyx")
3870 writeFile(FileName(filename));
3872 else if (params().isDocBook()) {
3873 runparams.nice = !put_in_tempdir;
3874 makeDocBookFile(FileName(filename), runparams);
3877 else if (backend_format == format || need_nice_file) {
3878 runparams.nice = true;
3879 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3880 if (d->cloned_buffer_)
3881 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3884 } else if (!lyxrc.tex_allows_spaces
3885 && contains(filePath(), ' ')) {
3886 Alert::error(_("File name error"),
3887 _("The directory path to the document cannot contain spaces."));
3888 return ExportTexPathHasSpaces;
3890 runparams.nice = false;
3891 bool const success = makeLaTeXFile(
3892 FileName(filename), filePath(), runparams);
3893 if (d->cloned_buffer_)
3894 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3899 string const error_type = (format == "program")
3900 ? "Build" : params().bufferFormat();
3901 ErrorList & error_list = d->errorLists[error_type];
3902 string const ext = formats.extension(format);
3903 FileName const tmp_result_file(changeExtension(filename, ext));
3904 bool const success = converters.convert(this, FileName(filename),
3905 tmp_result_file, FileName(absFileName()), backend_format, format,
3908 // Emit the signal to show the error list or copy it back to the
3909 // cloned Buffer so that it can be emitted afterwards.
3910 if (format != backend_format) {
3911 if (d->cloned_buffer_) {
3912 d->cloned_buffer_->d->errorLists[error_type] =
3913 d->errorLists[error_type];
3916 // also to the children, in case of master-buffer-view
3917 ListOfBuffers clist = getDescendents();
3918 ListOfBuffers::const_iterator cit = clist.begin();
3919 ListOfBuffers::const_iterator const cen = clist.end();
3920 for (; cit != cen; ++cit) {
3921 if (d->cloned_buffer_) {
3922 // Enable reverse search by copying back the
3923 // texrow object to the cloned buffer.
3924 // FIXME: this is not thread safe.
3925 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3926 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3927 (*cit)->d->errorLists[error_type];
3929 (*cit)->errors(error_type, true);
3933 if (d->cloned_buffer_) {
3934 // Enable reverse dvi or pdf to work by copying back the texrow
3935 // object to the cloned buffer.
3936 // FIXME: There is a possibility of concurrent access to texrow
3937 // here from the main GUI thread that should be securized.
3938 d->cloned_buffer_->d->texrow = d->texrow;
3939 string const error_type = params().bufferFormat();
3940 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3944 return ExportConverterError;
3946 if (put_in_tempdir) {
3947 result_file = tmp_result_file.absFileName();
3948 return ExportSuccess;
3951 if (dest_filename.empty())
3952 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3954 result_file = dest_filename;
3955 // We need to copy referenced files (e. g. included graphics
3956 // if format == "dvi") to the result dir.
3957 vector<ExportedFile> const files =
3958 runparams.exportdata->externalFiles(format);
3959 string const dest = runparams.export_folder.empty() ?
3960 onlyPath(result_file) : runparams.export_folder;
3961 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3962 : force_overwrite == ALL_FILES;
3963 CopyStatus status = use_force ? FORCE : SUCCESS;
3965 vector<ExportedFile>::const_iterator it = files.begin();
3966 vector<ExportedFile>::const_iterator const en = files.end();
3967 for (; it != en && status != CANCEL; ++it) {
3968 string const fmt = formats.getFormatFromFile(it->sourceName);
3969 string fixedName = it->exportName;
3970 if (!runparams.export_folder.empty()) {
3971 // Relative pathnames starting with ../ will be sanitized
3972 // if exporting to a different folder
3973 while (fixedName.substr(0, 3) == "../")
3974 fixedName = fixedName.substr(3, fixedName.length() - 3);
3976 FileName fixedFileName = makeAbsPath(fixedName, dest);
3977 fixedFileName.onlyPath().createPath();
3978 status = copyFile(fmt, it->sourceName,
3980 it->exportName, status == FORCE,
3981 runparams.export_folder.empty());
3984 if (status == CANCEL) {
3985 message(_("Document export cancelled."));
3986 return ExportCancel;
3989 if (tmp_result_file.exists()) {
3990 // Finally copy the main file
3991 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3992 : force_overwrite != NO_FILES;
3993 if (status == SUCCESS && use_force)
3995 status = copyFile(format, tmp_result_file,
3996 FileName(result_file), result_file,
3998 if (status == CANCEL) {
3999 message(_("Document export cancelled."));
4000 return ExportCancel;
4002 message(bformat(_("Document exported as %1$s "
4004 formats.prettyName(format),
4005 makeDisplayPath(result_file)));
4008 // This must be a dummy converter like fax (bug 1888)
4009 message(bformat(_("Document exported as %1$s"),
4010 formats.prettyName(format)));
4013 return ExportSuccess;
4017 Buffer::ExportStatus Buffer::preview(string const & format) const
4019 bool const update_unincluded =
4020 params().maintain_unincluded_children
4021 && !params().getIncludedChildren().empty();
4022 return preview(format, update_unincluded);
4025 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4027 MarkAsExporting exporting(this);
4029 // (1) export with all included children (omit \includeonly)
4031 ExportStatus const status = doExport(format, true, true, result_file);
4032 if (status != ExportSuccess)
4035 // (2) export with included children only
4036 ExportStatus const status = doExport(format, true, false, result_file);
4037 if (status != ExportSuccess)
4039 if (!formats.view(*this, FileName(result_file), format))
4040 return PreviewError;
4041 return PreviewSuccess;
4045 Buffer::ReadStatus Buffer::extractFromVC()
4047 bool const found = LyXVC::file_not_found_hook(d->filename);
4049 return ReadFileNotFound;
4050 if (!d->filename.isReadableFile())
4056 Buffer::ReadStatus Buffer::loadEmergency()
4058 FileName const emergencyFile = getEmergencyFileName();
4059 if (!emergencyFile.exists()
4060 || emergencyFile.lastModified() <= d->filename.lastModified())
4061 return ReadFileNotFound;
4063 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4064 docstring const text = bformat(_("An emergency save of the document "
4065 "%1$s exists.\n\nRecover emergency save?"), file);
4067 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4068 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4074 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4075 bool const success = (ret_llf == ReadSuccess);
4078 Alert::warning(_("File is read-only"),
4079 bformat(_("An emergency file is successfully loaded, "
4080 "but the original file %1$s is marked read-only. "
4081 "Please make sure to save the document as a different "
4082 "file."), from_utf8(d->filename.absFileName())));
4085 lyxvc().file_found_hook(d->filename);
4086 str = _("Document was successfully recovered.");
4088 str = _("Document was NOT successfully recovered.");
4089 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4090 makeDisplayPath(emergencyFile.absFileName()));
4092 int const del_emerg =
4093 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4094 _("&Remove"), _("&Keep"));
4095 if (del_emerg == 0) {
4096 emergencyFile.removeFile();
4098 Alert::warning(_("Emergency file deleted"),
4099 _("Do not forget to save your file now!"), true);
4101 return success ? ReadSuccess : ReadEmergencyFailure;
4104 int const del_emerg =
4105 Alert::prompt(_("Delete emergency file?"),
4106 _("Remove emergency file now?"), 1, 1,
4107 _("&Remove"), _("&Keep"));
4109 emergencyFile.removeFile();
4110 return ReadOriginal;
4120 Buffer::ReadStatus Buffer::loadAutosave()
4122 // Now check if autosave file is newer.
4123 FileName const autosaveFile = getAutosaveFileName();
4124 if (!autosaveFile.exists()
4125 || autosaveFile.lastModified() <= d->filename.lastModified())
4126 return ReadFileNotFound;
4128 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4129 docstring const text = bformat(_("The backup of the document %1$s "
4130 "is newer.\n\nLoad the backup instead?"), file);
4131 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4132 _("&Load backup"), _("Load &original"), _("&Cancel"));
4137 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4138 // the file is not saved if we load the autosave file.
4139 if (ret_llf == ReadSuccess) {
4141 Alert::warning(_("File is read-only"),
4142 bformat(_("A backup file is successfully loaded, "
4143 "but the original file %1$s is marked read-only. "
4144 "Please make sure to save the document as a "
4146 from_utf8(d->filename.absFileName())));
4149 lyxvc().file_found_hook(d->filename);
4152 return ReadAutosaveFailure;
4155 // Here we delete the autosave
4156 autosaveFile.removeFile();
4157 return ReadOriginal;
4165 Buffer::ReadStatus Buffer::loadLyXFile()
4167 if (!d->filename.isReadableFile()) {
4168 ReadStatus const ret_rvc = extractFromVC();
4169 if (ret_rvc != ReadSuccess)
4173 ReadStatus const ret_re = loadEmergency();
4174 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4177 ReadStatus const ret_ra = loadAutosave();
4178 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4181 return loadThisLyXFile(d->filename);
4185 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4187 return readFile(fn);
4191 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4193 TeXErrors::Errors::const_iterator it = terr.begin();
4194 TeXErrors::Errors::const_iterator end = terr.end();
4195 ListOfBuffers clist = getDescendents();
4196 ListOfBuffers::const_iterator cen = clist.end();
4198 for (; it != end; ++it) {
4201 int errorRow = it->error_in_line;
4202 Buffer const * buf = 0;
4204 if (it->child_name.empty())
4205 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4207 // The error occurred in a child
4208 ListOfBuffers::const_iterator cit = clist.begin();
4209 for (; cit != cen; ++cit) {
4210 string const child_name =
4211 DocFileName(changeExtension(
4212 (*cit)->absFileName(), "tex")).
4214 if (it->child_name != child_name)
4216 (*cit)->d->texrow.getIdFromRow(errorRow,
4217 id_start, pos_start);
4218 if (id_start != -1) {
4219 buf = d->cloned_buffer_
4220 ? (*cit)->d->cloned_buffer_->d->owner_
4221 : (*cit)->d->owner_;
4232 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4233 } while (found && id_start == id_end && pos_start == pos_end);
4235 if (id_start != id_end) {
4236 // Next registered position is outside the inset where
4237 // the error occurred, so signal end-of-paragraph
4241 errorList.push_back(ErrorItem(it->error_desc,
4242 it->error_text, id_start, pos_start, pos_end, buf));
4247 void Buffer::setBuffersForInsets() const
4249 inset().setBuffer(const_cast<Buffer &>(*this));
4253 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4255 // Use the master text class also for child documents
4256 Buffer const * const master = masterBuffer();
4257 DocumentClass const & textclass = master->params().documentClass();
4259 // do this only if we are the top-level Buffer
4261 reloadBibInfoCache();
4263 // keep the buffers to be children in this set. If the call from the
4264 // master comes back we can see which of them were actually seen (i.e.
4265 // via an InsetInclude). The remaining ones in the set need still be updated.
4266 static std::set<Buffer const *> bufToUpdate;
4267 if (scope == UpdateMaster) {
4268 // If this is a child document start with the master
4269 if (master != this) {
4270 bufToUpdate.insert(this);
4271 master->updateBuffer(UpdateMaster, utype);
4272 // Do this here in case the master has no gui associated with it. Then,
4273 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4274 if (!master->d->gui_)
4277 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4278 if (bufToUpdate.find(this) == bufToUpdate.end())
4282 // start over the counters in the master
4283 textclass.counters().reset();
4286 // update will be done below for this buffer
4287 bufToUpdate.erase(this);
4289 // update all caches
4290 clearReferenceCache();
4293 Buffer & cbuf = const_cast<Buffer &>(*this);
4295 LASSERT(!text().paragraphs().empty(), /**/);
4298 ParIterator parit = cbuf.par_iterator_begin();
4299 updateBuffer(parit, utype);
4302 // TocBackend update will be done later.
4305 d->bibinfo_cache_valid_ = true;
4306 d->cite_labels_valid_ = true;
4307 cbuf.tocBackend().update(utype == OutputUpdate);
4308 if (scope == UpdateMaster)
4309 cbuf.structureChanged();
4313 static depth_type getDepth(DocIterator const & it)
4315 depth_type depth = 0;
4316 for (size_t i = 0 ; i < it.depth() ; ++i)
4317 if (!it[i].inset().inMathed())
4318 depth += it[i].paragraph().getDepth() + 1;
4319 // remove 1 since the outer inset does not count
4323 static depth_type getItemDepth(ParIterator const & it)
4325 Paragraph const & par = *it;
4326 LabelType const labeltype = par.layout().labeltype;
4328 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4331 // this will hold the lowest depth encountered up to now.
4332 depth_type min_depth = getDepth(it);
4333 ParIterator prev_it = it;
4336 --prev_it.top().pit();
4338 // start of nested inset: go to outer par
4340 if (prev_it.empty()) {
4341 // start of document: nothing to do
4346 // We search for the first paragraph with same label
4347 // that is not more deeply nested.
4348 Paragraph & prev_par = *prev_it;
4349 depth_type const prev_depth = getDepth(prev_it);
4350 if (labeltype == prev_par.layout().labeltype) {
4351 if (prev_depth < min_depth)
4352 return prev_par.itemdepth + 1;
4353 if (prev_depth == min_depth)
4354 return prev_par.itemdepth;
4356 min_depth = min(min_depth, prev_depth);
4357 // small optimization: if we are at depth 0, we won't
4358 // find anything else
4359 if (prev_depth == 0)
4365 static bool needEnumCounterReset(ParIterator const & it)
4367 Paragraph const & par = *it;
4368 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4369 depth_type const cur_depth = par.getDepth();
4370 ParIterator prev_it = it;
4371 while (prev_it.pit()) {
4372 --prev_it.top().pit();
4373 Paragraph const & prev_par = *prev_it;
4374 if (prev_par.getDepth() <= cur_depth)
4375 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4377 // start of nested inset: reset
4382 // set the label of a paragraph. This includes the counters.
4383 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4385 BufferParams const & bp = owner_->masterBuffer()->params();
4386 DocumentClass const & textclass = bp.documentClass();
4387 Paragraph & par = it.paragraph();
4388 Layout const & layout = par.layout();
4389 Counters & counters = textclass.counters();
4391 if (par.params().startOfAppendix()) {
4392 // We want to reset the counter corresponding to toplevel sectioning
4393 Layout const & lay = textclass.getTOCLayout();
4394 docstring const cnt = lay.counter;
4396 counters.reset(cnt);
4397 counters.appendix(true);
4399 par.params().appendix(counters.appendix());
4401 // Compute the item depth of the paragraph
4402 par.itemdepth = getItemDepth(it);
4404 if (layout.margintype == MARGIN_MANUAL) {
4405 if (par.params().labelWidthString().empty())
4406 par.params().labelWidthString(par.expandLabel(layout, bp));
4407 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4408 // we do not need to do anything here, since the empty case is
4409 // handled during export.
4411 par.params().labelWidthString(docstring());
4414 switch(layout.labeltype) {
4415 case LABEL_ITEMIZE: {
4416 // At some point of time we should do something more
4417 // clever here, like:
4418 // par.params().labelString(
4419 // bp.user_defined_bullet(par.itemdepth).getText());
4420 // for now, use a simple hardcoded label
4421 docstring itemlabel;
4422 switch (par.itemdepth) {
4424 itemlabel = char_type(0x2022);
4427 itemlabel = char_type(0x2013);
4430 itemlabel = char_type(0x2217);
4433 itemlabel = char_type(0x2219); // or 0x00b7
4436 par.params().labelString(itemlabel);
4440 case LABEL_ENUMERATE: {
4441 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4443 switch (par.itemdepth) {
4452 enumcounter += "iv";
4455 // not a valid enumdepth...
4459 // Maybe we have to reset the enumeration counter.
4460 if (needEnumCounterReset(it))
4461 counters.reset(enumcounter);
4462 counters.step(enumcounter, utype);
4464 string const & lang = par.getParLanguage(bp)->code();
4465 par.params().labelString(counters.theCounter(enumcounter, lang));
4470 case LABEL_SENSITIVE: {
4471 string const & type = counters.current_float();
4472 docstring full_label;
4474 full_label = owner_->B_("Senseless!!! ");
4476 docstring name = owner_->B_(textclass.floats().getType(type).name());
4477 if (counters.hasCounter(from_utf8(type))) {
4478 string const & lang = par.getParLanguage(bp)->code();
4479 counters.step(from_utf8(type), utype);
4480 full_label = bformat(from_ascii("%1$s %2$s:"),
4482 counters.theCounter(from_utf8(type), lang));
4484 full_label = bformat(from_ascii("%1$s #:"), name);
4486 par.params().labelString(full_label);
4490 case LABEL_NO_LABEL:
4491 par.params().labelString(docstring());
4495 case LABEL_CENTERED:
4496 case LABEL_STATIC: {
4497 docstring const & lcounter = layout.counter;
4498 if (!lcounter.empty()) {
4499 if (layout.toclevel <= bp.secnumdepth
4500 && (layout.latextype != LATEX_ENVIRONMENT
4501 || it.text()->isFirstInSequence(it.pit()))) {
4502 if (counters.hasCounter(lcounter))
4503 counters.step(lcounter, utype);
4504 par.params().labelString(par.expandLabel(layout, bp));
4506 par.params().labelString(docstring());
4508 par.params().labelString(par.expandLabel(layout, bp));
4514 par.params().labelString(par.expandLabel(layout, bp));
4519 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4521 LASSERT(parit.pit() == 0, /**/);
4523 // Set the position of the text in the buffer to be able
4524 // to resolve macros in it.
4525 parit.text()->setMacrocontextPosition(parit);
4527 depth_type maxdepth = 0;
4528 pit_type const lastpit = parit.lastpit();
4529 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4530 // reduce depth if necessary
4531 if (parit->params().depth() > maxdepth) {
4532 /** FIXME: this function is const, but
4533 * nevertheless it modifies the buffer. To be
4534 * cleaner, one should modify the buffer in
4535 * another function, which is actually
4536 * non-const. This would however be costly in
4537 * terms of code duplication.
4539 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4540 parit->params().depth(maxdepth);
4542 maxdepth = parit->getMaxDepthAfter();
4544 if (utype == OutputUpdate) {
4545 // track the active counters
4546 // we have to do this for the master buffer, since the local
4547 // buffer isn't tracking anything.
4548 masterBuffer()->params().documentClass().counters().
4549 setActiveLayout(parit->layout());
4552 // set the counter for this paragraph
4553 d->setLabel(parit, utype);
4556 InsetList::const_iterator iit = parit->insetList().begin();
4557 InsetList::const_iterator end = parit->insetList().end();
4558 for (; iit != end; ++iit) {
4559 parit.pos() = iit->pos;
4560 iit->inset->updateBuffer(parit, utype);
4566 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4567 WordLangTuple & word_lang, docstring_list & suggestions) const
4571 suggestions.clear();
4572 word_lang = WordLangTuple();
4573 bool const to_end = to.empty();
4574 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4575 // OK, we start from here.
4576 for (; from != end; from.forwardPos()) {
4577 // We are only interested in text so remove the math CursorSlice.
4578 while (from.inMathed()) {
4582 // If from is at the end of the document (which is possible
4583 // when leaving the mathed) LyX will crash later otherwise.
4584 if (from.atEnd() || (!to_end && from >= end))
4587 from.paragraph().spellCheck();
4588 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4589 if (SpellChecker::misspelled(res)) {
4594 // Do not increase progress when from == to, otherwise the word
4595 // count will be wrong.
4605 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4607 bool inword = false;
4612 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4613 if (!dit.inTexted()) {
4618 Paragraph const & par = dit.paragraph();
4619 pos_type const pos = dit.pos();
4621 // Copied and adapted from isWordSeparator() in Paragraph
4622 if (pos == dit.lastpos()) {
4625 Inset const * ins = par.getInset(pos);
4626 if (ins && skipNoOutput && !ins->producesOutput()) {
4629 // stop if end of range was skipped
4630 if (!to.atEnd() && dit >= to)
4633 } else if (!par.isDeleted(pos)) {
4634 if (par.isWordSeparator(pos))
4640 if (ins && ins->isLetter())
4642 else if (ins && ins->isSpace())
4645 char_type const c = par.getChar(pos);
4646 if (isPrintableNonspace(c))
4648 else if (isSpace(c))
4658 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4660 d->updateStatistics(from, to, skipNoOutput);
4664 int Buffer::wordCount() const
4666 return d->wordCount();
4670 int Buffer::charCount(bool with_blanks) const
4672 return d->charCount(with_blanks);
4676 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4679 // c.f. bug http://www.lyx.org/trac/ticket/6587
4680 removeAutosaveFile();
4681 // e.g., read-only status could have changed due to version control
4682 d->filename.refresh();
4683 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4685 // clear parent. this will get reset if need be.
4687 ReadStatus const status = loadLyXFile();
4688 if (status == ReadSuccess) {
4693 message(bformat(_("Document %1$s reloaded."), disp_fn));
4697 message(bformat(_("Could not reload document %1$s."), disp_fn));
4707 bool Buffer::saveAs(FileName const & fn)
4709 FileName const old_name = fileName();
4710 FileName const old_auto = getAutosaveFileName();
4711 bool const old_unnamed = isUnnamed();
4718 // bring the autosave file with us, just in case.
4719 moveAutosaveFile(old_auto);
4720 // validate version control data and
4721 // correct buffer title
4722 lyxvc().file_found_hook(fileName());
4724 // the file has now been saved to the new location.
4725 // we need to check that the locations of child buffers
4727 checkChildBuffers();
4728 checkMasterBuffer();
4732 // reset the old filename and unnamed state
4733 setFileName(old_name);
4734 setUnnamed(old_unnamed);
4740 // FIXME We could do better here, but it is complicated. What would be
4741 // nice is to offer either (a) to save the child buffer to an appropriate
4742 // location, so that it would "move with the master", or else (b) to update
4743 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4744 // complicated, because the code for this lives in GuiView.
4745 void Buffer::checkChildBuffers()
4747 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4748 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4749 for (; it != en; ++it) {
4750 DocIterator dit = it->second;
4751 Buffer * cbuf = const_cast<Buffer *>(it->first);
4752 if (!cbuf || !theBufferList().isLoaded(cbuf))
4754 Inset * inset = dit.nextInset();
4755 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4756 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4757 docstring const & incfile = inset_inc->getParam("filename");
4758 string oldloc = cbuf->absFileName();
4759 string newloc = makeAbsPath(to_utf8(incfile),
4760 onlyPath(absFileName())).absFileName();
4761 if (oldloc == newloc)
4763 // the location of the child file is incorrect.
4764 Alert::warning(_("Included File Invalid"),
4765 bformat(_("Saving this document to a new location has made the file:\n"
4767 "inaccessible. You will need to update the included filename."),
4768 from_utf8(oldloc)));
4770 inset_inc->setChildBuffer(0);
4772 // invalidate cache of children
4773 d->children_positions.clear();
4774 d->position_to_children.clear();
4778 // If a child has been saved under a different name/path, it might have been
4779 // orphaned. Therefore the master needs to be reset (bug 8161).
4780 void Buffer::checkMasterBuffer()
4782 Buffer const * const master = masterBuffer();
4786 // necessary to re-register the child (bug 5873)
4787 // FIXME: clean up updateMacros (here, only
4788 // child registering is needed).
4789 master->updateMacros();
4790 // (re)set master as master buffer, but only
4791 // if we are a real child
4792 if (master->isChild(this))