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"
31 #include "BufferEncodings.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"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.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;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Keeps track of old buffer filePath() for save-as operations
255 /** Keeps track of the path of local layout files.
256 * If possible, it is always relative to the buffer path.
257 * Empty for layouts in system or user directory.
259 string layout_position;
261 /// Container for all sort of Buffer dependant errors.
262 map<string, ErrorList> errorLists;
264 /// timestamp and checksum used to test if the file has been externally
265 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
267 unsigned long checksum_;
270 frontend::WorkAreaManager * wa_;
272 frontend::GuiBufferDelegate * gui_;
277 /// A cache for the bibfiles (including bibfiles of loaded child
278 /// documents), needed for appropriate update of natbib labels.
279 mutable support::FileNameList bibfiles_cache_;
281 // FIXME The caching mechanism could be improved. At present, we have a
282 // cache for each Buffer, that caches all the bibliography info for that
283 // Buffer. A more efficient solution would be to have a global cache per
284 // file, and then to construct the Buffer's bibinfo from that.
285 /// A cache for bibliography info
286 mutable BiblioInfo bibinfo_;
287 /// whether the bibinfo cache is valid
288 mutable bool bibinfo_cache_valid_;
289 /// whether the bibfile cache is valid
290 mutable bool bibfile_cache_valid_;
291 /// Cache of timestamps of .bib files
292 map<FileName, time_t> bibfile_status_;
293 /// Indicates whether the bibinfo has changed since the last time
294 /// we ran updateBuffer(), i.e., whether citation labels may need
296 mutable bool cite_labels_valid_;
298 /// These two hold the file name and format, written to by
299 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
300 FileName preview_file_;
301 string preview_format_;
302 /// If there was an error when previewing, on the next preview we do
303 /// a fresh compile (e.g. in case the user installed a package that
307 mutable RefCache ref_cache_;
309 /// our Text that should be wrapped in an InsetText
313 PreviewLoader * preview_loader_;
315 /// This is here to force the test to be done whenever parent_buffer
317 Buffer const * parent() const
319 // ignore_parent temporarily "orphans" a buffer
320 // (e.g. if a child is compiled standalone)
323 // if parent_buffer is not loaded, then it has been unloaded,
324 // which means that parent_buffer is an invalid pointer. So we
325 // set it to null in that case.
326 // however, the BufferList doesn't know about cloned buffers, so
327 // they will always be regarded as unloaded. in that case, we hope
329 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
331 return parent_buffer;
335 void setParent(Buffer const * pb)
337 if (parent_buffer == pb)
340 if (!cloned_buffer_ && parent_buffer && pb)
341 LYXERR0("Warning: a buffer should not have two parents!");
343 if (!cloned_buffer_ && parent_buffer) {
344 parent_buffer->invalidateBibfileCache();
345 parent_buffer->invalidateBibinfoCache();
349 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
350 /// This one is useful for preview detached in a thread.
351 Buffer const * cloned_buffer_;
353 CloneList * clone_list_;
354 /// are we in the process of exporting this buffer?
355 mutable bool doing_export;
357 /// compute statistics
358 /// \p from initial position
359 /// \p to points to the end position
360 void updateStatistics(DocIterator & from, DocIterator & to,
361 bool skipNoOutput = true);
362 /// statistics accessor functions
363 int wordCount() const
367 int charCount(bool with_blanks) const
370 + (with_blanks ? blank_count_ : 0);
374 /// So we can force access via the accessors.
375 mutable Buffer const * parent_buffer;
384 /// Creates the per buffer temporary directory
385 static FileName createBufferTmpDir()
387 // FIXME This would be the ideal application for a TempDir class (like
388 // TempFile but for directories)
393 Mutex::Locker locker(&mutex);
394 counter = convert<string>(count++);
396 // We are in our own directory. Why bother to mangle name?
397 // In fact I wrote this code to circumvent a problematic behaviour
398 // (bug?) of EMX mkstemp().
399 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
402 if (!tmpfl.createDirectory(0777)) {
403 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
404 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
405 from_utf8(tmpfl.absFileName())));
411 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
412 Buffer const * cloned_buffer)
413 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
414 internal_buffer(false), read_only(readonly_), filename(file),
415 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
416 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
417 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
418 cite_labels_valid_(false), inset(0), preview_loader_(0),
419 cloned_buffer_(cloned_buffer), clone_list_(0),
420 doing_export(false), parent_buffer(0),
421 word_count_(0), char_count_(0), blank_count_(0)
423 if (!cloned_buffer_) {
424 temppath = createBufferTmpDir();
425 lyxvc.setBuffer(owner_);
427 wa_ = new frontend::WorkAreaManager;
430 temppath = cloned_buffer_->d->temppath;
431 file_fully_loaded = true;
432 params = cloned_buffer_->d->params;
433 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
434 bibinfo_ = cloned_buffer_->d->bibinfo_;
435 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
436 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
437 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
438 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
439 unnamed = cloned_buffer_->d->unnamed;
440 internal_buffer = cloned_buffer_->d->internal_buffer;
441 layout_position = cloned_buffer_->d->layout_position;
442 preview_file_ = cloned_buffer_->d->preview_file_;
443 preview_format_ = cloned_buffer_->d->preview_format_;
444 preview_error_ = cloned_buffer_->d->preview_error_;
448 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
449 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
451 LYXERR(Debug::INFO, "Buffer::Buffer()");
453 d->inset = new InsetText(*cloned_buffer->d->inset);
454 d->inset->setBuffer(*this);
455 // FIXME: optimize this loop somewhat, maybe by creating a new
456 // general recursive Inset::setId().
457 DocIterator it = doc_iterator_begin(this);
458 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
459 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
460 it.paragraph().setId(cloned_it.paragraph().id());
462 d->inset = new InsetText(this);
463 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
469 LYXERR(Debug::INFO, "Buffer::~Buffer()");
470 // here the buffer should take care that it is
471 // saved properly, before it goes into the void.
473 // GuiView already destroyed
477 // No need to do additional cleanups for internal buffer.
483 // this is in case of recursive includes: we won't try to delete
484 // ourselves as a child.
485 d->clone_list_->erase(this);
486 // loop over children
487 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
488 Impl::BufferPositionMap::iterator end = d->children_positions.end();
489 for (; it != end; ++it) {
490 Buffer * child = const_cast<Buffer *>(it->first);
491 if (d->clone_list_->erase(child))
494 // if we're the master buffer, then we should get rid of the list
497 // If this is not empty, we have leaked something. Worse, one of the
498 // children still has a reference to this list. But we will try to
499 // continue, rather than shut down.
500 LATTEST(d->clone_list_->empty());
501 list<CloneList *>::iterator it =
502 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
503 if (it == cloned_buffers.end()) {
504 // We will leak in this case, but it is safe to continue.
507 cloned_buffers.erase(it);
508 delete d->clone_list_;
510 // FIXME Do we really need to do this right before we delete d?
511 // clear references to children in macro tables
512 d->children_positions.clear();
513 d->position_to_children.clear();
515 // loop over children
516 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
517 Impl::BufferPositionMap::iterator end = d->children_positions.end();
518 for (; it != end; ++it) {
519 Buffer * child = const_cast<Buffer *>(it->first);
520 if (theBufferList().isLoaded(child))
521 theBufferList().releaseChild(this, child);
525 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
526 msg += emergencyWrite();
527 Alert::warning(_("Attempting to close changed document!"), msg);
530 // FIXME Do we really need to do this right before we delete d?
531 // clear references to children in macro tables
532 d->children_positions.clear();
533 d->position_to_children.clear();
535 if (!d->temppath.destroyDirectory()) {
536 Alert::warning(_("Could not remove temporary directory"),
537 bformat(_("Could not remove the temporary directory %1$s"),
538 from_utf8(d->temppath.absFileName())));
547 Buffer * Buffer::cloneFromMaster() const
550 cloned_buffers.push_back(new CloneList);
551 CloneList * clones = cloned_buffers.back();
553 masterBuffer()->cloneWithChildren(bufmap, clones);
555 // make sure we got cloned
556 BufferMap::const_iterator bit = bufmap.find(this);
557 LASSERT(bit != bufmap.end(), return 0);
558 Buffer * cloned_buffer = bit->second;
560 return cloned_buffer;
564 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
566 // have we already been cloned?
567 if (bufmap.find(this) != bufmap.end())
570 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
572 // The clone needs its own DocumentClass, since running updateBuffer() will
573 // modify it, and we would otherwise be sharing it with the original Buffer.
574 buffer_clone->params().makeDocumentClass(true);
576 cap::switchBetweenClasses(
577 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
578 static_cast<InsetText &>(buffer_clone->inset()), el);
580 bufmap[this] = buffer_clone;
581 clones->insert(buffer_clone);
582 buffer_clone->d->clone_list_ = clones;
583 buffer_clone->d->macro_lock = true;
584 buffer_clone->d->children_positions.clear();
586 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
587 // math macro caches need to be rethought and simplified.
588 // I am not sure wether we should handle Buffer cloning here or in BufferList.
589 // Right now BufferList knows nothing about buffer clones.
590 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
591 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
592 for (; it != end; ++it) {
593 DocIterator dit = it->first.clone(buffer_clone);
594 dit.setBuffer(buffer_clone);
595 Buffer * child = const_cast<Buffer *>(it->second.buffer);
597 child->cloneWithChildren(bufmap, clones);
598 BufferMap::iterator const bit = bufmap.find(child);
599 LASSERT(bit != bufmap.end(), continue);
600 Buffer * child_clone = bit->second;
602 Inset * inset = dit.nextInset();
603 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
604 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
605 inset_inc->setChildBuffer(child_clone);
606 child_clone->d->setParent(buffer_clone);
607 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
608 buffer_clone->setChild(dit, child_clone);
610 buffer_clone->d->macro_lock = false;
615 Buffer * Buffer::cloneBufferOnly() const {
616 cloned_buffers.push_back(new CloneList);
617 CloneList * clones = cloned_buffers.back();
618 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
620 // The clone needs its own DocumentClass, since running updateBuffer() will
621 // modify it, and we would otherwise be sharing it with the original Buffer.
622 buffer_clone->params().makeDocumentClass(true);
624 cap::switchBetweenClasses(
625 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
626 static_cast<InsetText &>(buffer_clone->inset()), el);
628 clones->insert(buffer_clone);
629 buffer_clone->d->clone_list_ = clones;
631 // we won't be cloning the children
632 buffer_clone->d->children_positions.clear();
637 bool Buffer::isClone() const
639 return d->cloned_buffer_;
643 void Buffer::changed(bool update_metrics) const
646 d->wa_->redrawAll(update_metrics);
650 frontend::WorkAreaManager & Buffer::workAreaManager() const
657 Text & Buffer::text() const
659 return d->inset->text();
663 Inset & Buffer::inset() const
669 BufferParams & Buffer::params()
675 BufferParams const & Buffer::params() const
681 BufferParams const & Buffer::masterParams() const
683 if (masterBuffer() == this)
686 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
687 // Copy child authors to the params. We need those pointers.
688 AuthorList const & child_authors = params().authors();
689 AuthorList::Authors::const_iterator it = child_authors.begin();
690 for (; it != child_authors.end(); ++it)
691 mparams.authors().record(*it);
696 double Buffer::fontScalingFactor() const
698 return isExporting() ? 75.0 * params().html_math_img_scale
699 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
703 ParagraphList & Buffer::paragraphs()
705 return text().paragraphs();
709 ParagraphList const & Buffer::paragraphs() const
711 return text().paragraphs();
715 LyXVC & Buffer::lyxvc()
721 LyXVC const & Buffer::lyxvc() const
727 string const Buffer::temppath() const
729 return d->temppath.absFileName();
733 TexRow & Buffer::texrow()
739 TexRow const & Buffer::texrow() const
745 TocBackend & Buffer::tocBackend() const
747 return d->toc_backend;
751 Undo & Buffer::undo()
757 void Buffer::setChild(DocIterator const & dit, Buffer * child)
759 d->children_positions[child] = dit;
763 string Buffer::latexName(bool const no_path) const
765 FileName latex_name =
766 makeLatexName(d->exportFileName());
767 return no_path ? latex_name.onlyFileName()
768 : latex_name.absFileName();
772 FileName Buffer::Impl::exportFileName() const
774 docstring const branch_suffix =
775 params.branchlist().getFileNameSuffix();
776 if (branch_suffix.empty())
779 string const name = filename.onlyFileNameWithoutExt()
780 + to_utf8(branch_suffix);
781 FileName res(filename.onlyPath().absFileName() + "/" + name);
782 res.changeExtension(filename.extension());
788 string Buffer::logName(LogType * type) const
790 string const filename = latexName(false);
792 if (filename.empty()) {
798 string const path = temppath();
800 FileName const fname(addName(temppath(),
801 onlyFileName(changeExtension(filename,
804 // FIXME: how do we know this is the name of the build log?
805 FileName const bname(
806 addName(path, onlyFileName(
807 changeExtension(filename,
808 formats.extension(params().bufferFormat()) + ".out"))));
810 // Also consider the master buffer log file
811 FileName masterfname = fname;
812 LogType mtype = latexlog;
813 if (masterBuffer() != this) {
814 string const mlogfile = masterBuffer()->logName(&mtype);
815 masterfname = FileName(mlogfile);
818 // If no Latex log or Build log is newer, show Build log
819 if (bname.exists() &&
820 ((!fname.exists() && !masterfname.exists())
821 || (fname.lastModified() < bname.lastModified()
822 && masterfname.lastModified() < bname.lastModified()))) {
823 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
826 return bname.absFileName();
827 // If we have a newer master file log or only a master log, show this
828 } else if (fname != masterfname
829 && (!fname.exists() && (masterfname.exists()
830 || fname.lastModified() < masterfname.lastModified()))) {
831 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
834 return masterfname.absFileName();
836 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
839 return fname.absFileName();
843 void Buffer::setReadonly(bool const flag)
845 if (d->read_only != flag) {
852 void Buffer::setFileName(FileName const & fname)
854 bool const changed = fname != d->filename;
857 lyxvc().file_found_hook(fname);
858 setReadonly(d->filename.isReadOnly());
864 int Buffer::readHeader(Lexer & lex)
866 int unknown_tokens = 0;
868 int begin_header_line = -1;
870 // Initialize parameters that may be/go lacking in header:
871 params().branchlist().clear();
872 params().preamble.erase();
873 params().options.erase();
874 params().master.erase();
875 params().float_placement.erase();
876 params().paperwidth.erase();
877 params().paperheight.erase();
878 params().leftmargin.erase();
879 params().rightmargin.erase();
880 params().topmargin.erase();
881 params().bottommargin.erase();
882 params().headheight.erase();
883 params().headsep.erase();
884 params().footskip.erase();
885 params().columnsep.erase();
886 params().fonts_cjk.erase();
887 params().listings_params.clear();
888 params().clearLayoutModules();
889 params().clearRemovedModules();
890 params().clearIncludedChildren();
891 params().pdfoptions().clear();
892 params().indiceslist().clear();
893 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
894 params().isbackgroundcolor = false;
895 params().fontcolor = RGBColor(0, 0, 0);
896 params().isfontcolor = false;
897 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
898 params().boxbgcolor = RGBColor(0xFF, 0, 0);
899 params().html_latex_start.clear();
900 params().html_latex_end.clear();
901 params().html_math_img_scale = 1.0;
902 params().output_sync_macro.erase();
903 params().setLocalLayout(string(), false);
904 params().setLocalLayout(string(), true);
906 for (int i = 0; i < 4; ++i) {
907 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
908 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
911 ErrorList & errorList = d->errorLists["Parse"];
920 if (token == "\\end_header")
924 if (token == "\\begin_header") {
925 begin_header_line = line;
929 LYXERR(Debug::PARSER, "Handling document header token: `"
932 string const result =
933 params().readToken(lex, token, d->filename.onlyPath());
934 if (!result.empty()) {
935 if (token == "\\textclass") {
936 d->layout_position = result;
939 docstring const s = bformat(_("Unknown token: "
943 errorList.push_back(ErrorItem(_("Document header error"),
948 if (begin_header_line) {
949 docstring const s = _("\\begin_header is missing");
950 errorList.push_back(ErrorItem(_("Document header error"),
954 params().makeDocumentClass();
956 return unknown_tokens;
961 // changed to be public and have one parameter
962 // Returns true if "\end_document" is not read (Asger)
963 bool Buffer::readDocument(Lexer & lex)
965 ErrorList & errorList = d->errorLists["Parse"];
968 // remove dummy empty par
969 paragraphs().clear();
971 if (!lex.checkFor("\\begin_document")) {
972 docstring const s = _("\\begin_document is missing");
973 errorList.push_back(ErrorItem(_("Document header error"),
979 if (params().output_changes) {
980 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
981 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
982 LaTeXFeatures::isAvailable("xcolor");
984 if (!dvipost && !xcolorulem) {
985 Alert::warning(_("Changes not shown in LaTeX output"),
986 _("Changes will not be highlighted in LaTeX output, "
987 "because neither dvipost nor xcolor/ulem are installed.\n"
988 "Please install these packages or redefine "
989 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
990 } else if (!xcolorulem) {
991 Alert::warning(_("Changes not shown in LaTeX output"),
992 _("Changes will not be highlighted in LaTeX output "
993 "when using pdflatex, because xcolor and ulem are not installed.\n"
994 "Please install both packages or redefine "
995 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
999 if (!parent() && !params().master.empty()) {
1000 FileName const master_file = makeAbsPath(params().master,
1001 onlyPath(absFileName()));
1002 if (isLyXFileName(master_file.absFileName())) {
1004 checkAndLoadLyXFile(master_file, true);
1006 // necessary e.g. after a reload
1007 // to re-register the child (bug 5873)
1008 // FIXME: clean up updateMacros (here, only
1009 // child registering is needed).
1010 master->updateMacros();
1011 // set master as master buffer, but only
1012 // if we are a real child
1013 if (master->isChild(this))
1015 // if the master is not fully loaded
1016 // it is probably just loading this
1017 // child. No warning needed then.
1018 else if (master->isFullyLoaded())
1019 LYXERR0("The master '"
1021 << "' assigned to this document ("
1023 << ") does not include "
1024 "this document. Ignoring the master assignment.");
1029 // assure we have a default index
1030 params().indiceslist().addDefault(B_("Index"));
1033 bool const res = text().read(lex, errorList, d->inset);
1035 // inform parent buffer about local macros
1037 Buffer const * pbuf = parent();
1038 UserMacroSet::const_iterator cit = usermacros.begin();
1039 UserMacroSet::const_iterator end = usermacros.end();
1040 for (; cit != end; ++cit)
1041 pbuf->usermacros.insert(*cit);
1045 updateMacroInstances(InternalUpdate);
1050 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1052 Format const * fmt = formats.getFormat(format);
1055 // It is important to use the correct extension here, since some
1056 // converters create a wrong output file otherwise (e.g. html2latex)
1057 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1058 FileName const name(tempfile.name());
1059 ofdocstream os(name.toFilesystemEncoding().c_str());
1060 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1061 bool const success = !(os << contents).fail();
1064 bool converted = false;
1066 params().compressed = false;
1068 // remove dummy empty par
1069 paragraphs().clear();
1071 converted = importFile(format, name, errorList);
1080 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1082 if (!theConverters().isReachable(format, "lyx"))
1085 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1086 FileName const lyx(tempfile.name());
1087 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1088 return readFile(lyx) == ReadSuccess;
1094 bool Buffer::readString(string const & s)
1096 params().compressed = false;
1099 istringstream is(s);
1101 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1102 FileName const fn = tempfile.name();
1105 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1107 if (success && file_format != LYX_FORMAT) {
1108 // We need to call lyx2lyx, so write the input to a file
1109 ofstream os(fn.toFilesystemEncoding().c_str());
1112 // lyxvc in readFile
1113 if (readFile(fn) != ReadSuccess)
1117 if (readDocument(lex))
1123 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1127 if (!lex.setFile(fname)) {
1128 Alert::error(_("File Not Found"),
1129 bformat(_("Unable to open file `%1$s'."),
1130 from_utf8(fn.absFileName())));
1131 return ReadFileNotFound;
1135 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1136 if (ret_plf != ReadSuccess)
1139 if (file_format != LYX_FORMAT) {
1141 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1142 if (ret_clf != ReadSuccess)
1144 return readFile(tmpFile);
1147 // FIXME: InsetInfo needs to know whether the file is under VCS
1148 // during the parse process, so this has to be done before.
1149 lyxvc().file_found_hook(d->filename);
1151 if (readDocument(lex)) {
1152 Alert::error(_("Document format failure"),
1153 bformat(_("%1$s ended unexpectedly, which means"
1154 " that it is probably corrupted."),
1155 from_utf8(fn.absFileName())));
1156 return ReadDocumentFailure;
1159 d->file_fully_loaded = true;
1160 d->read_only = !d->filename.isWritable();
1161 params().compressed = formats.isZippedFile(d->filename);
1167 bool Buffer::isFullyLoaded() const
1169 return d->file_fully_loaded;
1173 void Buffer::setFullyLoaded(bool value)
1175 d->file_fully_loaded = value;
1179 bool Buffer::lastPreviewError() const
1181 return d->preview_error_;
1185 PreviewLoader * Buffer::loader() const
1187 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1189 if (!d->preview_loader_)
1190 d->preview_loader_ = new PreviewLoader(*this);
1191 return d->preview_loader_;
1195 void Buffer::removePreviews() const
1197 delete d->preview_loader_;
1198 d->preview_loader_ = 0;
1202 void Buffer::updatePreviews() const
1204 PreviewLoader * ploader = loader();
1208 InsetIterator it = inset_iterator_begin(*d->inset);
1209 InsetIterator const end = inset_iterator_end(*d->inset);
1210 for (; it != end; ++it)
1211 it->addPreview(it, *ploader);
1213 ploader->startLoading();
1217 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1218 FileName const & fn, int & file_format) const
1220 if(!lex.checkFor("\\lyxformat")) {
1221 Alert::error(_("Document format failure"),
1222 bformat(_("%1$s is not a readable LyX document."),
1223 from_utf8(fn.absFileName())));
1224 return ReadNoLyXFormat;
1230 // LyX formats 217 and earlier were written as 2.17. This corresponds
1231 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1232 // these cases. See also: www.lyx.org/trac/changeset/1313.
1233 size_t dot = tmp_format.find_first_of(".,");
1234 if (dot != string::npos)
1235 tmp_format.erase(dot, 1);
1237 file_format = convert<int>(tmp_format);
1242 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1243 FileName & tmpfile, int from_format)
1245 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1246 tempfile.setAutoRemove(false);
1247 tmpfile = tempfile.name();
1248 if(tmpfile.empty()) {
1249 Alert::error(_("Conversion failed"),
1250 bformat(_("%1$s is from a different"
1251 " version of LyX, but a temporary"
1252 " file for converting it could"
1253 " not be created."),
1254 from_utf8(fn.absFileName())));
1255 return LyX2LyXNoTempFile;
1258 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1259 if (lyx2lyx.empty()) {
1260 Alert::error(_("Conversion script not found"),
1261 bformat(_("%1$s is from a different"
1262 " version of LyX, but the"
1263 " conversion script lyx2lyx"
1264 " could not be found."),
1265 from_utf8(fn.absFileName())));
1266 return LyX2LyXNotFound;
1270 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1271 ostringstream command;
1272 command << os::python()
1273 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1274 << " -t " << convert<string>(LYX_FORMAT)
1275 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1276 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1277 string const command_str = command.str();
1279 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1281 cmd_ret const ret = runCommand(command_str);
1282 if (ret.first != 0) {
1283 if (from_format < LYX_FORMAT) {
1284 Alert::error(_("Conversion script failed"),
1285 bformat(_("%1$s is from an older version"
1286 " of LyX and the lyx2lyx script"
1287 " failed to convert it."),
1288 from_utf8(fn.absFileName())));
1289 return LyX2LyXOlderFormat;
1291 Alert::error(_("Conversion script failed"),
1292 bformat(_("%1$s is from a newer version"
1293 " of LyX and the lyx2lyx script"
1294 " failed to convert it."),
1295 from_utf8(fn.absFileName())));
1296 return LyX2LyXNewerFormat;
1303 // Should probably be moved to somewhere else: BufferView? GuiView?
1304 bool Buffer::save() const
1306 docstring const file = makeDisplayPath(absFileName(), 20);
1307 d->filename.refresh();
1309 // check the read-only status before moving the file as a backup
1310 if (d->filename.exists()) {
1311 bool const read_only = !d->filename.isWritable();
1313 Alert::warning(_("File is read-only"),
1314 bformat(_("The file %1$s cannot be written because it "
1315 "is marked as read-only."), file));
1320 // ask if the disk file has been externally modified (use checksum method)
1321 if (fileName().exists() && isExternallyModified(checksum_method)) {
1323 bformat(_("Document %1$s has been externally modified. "
1324 "Are you sure you want to overwrite this file?"), file);
1325 int const ret = Alert::prompt(_("Overwrite modified file?"),
1326 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1331 // We don't need autosaves in the immediate future. (Asger)
1332 resetAutosaveTimers();
1334 // if the file does not yet exist, none of the backup activity
1335 // that follows is necessary
1336 if (!fileName().exists())
1337 return writeFile(fileName());
1339 // we first write the file to a new name, then move it to its
1340 // proper location once that has been done successfully. that
1341 // way we preserve the original file if something goes wrong.
1342 string const justname = fileName().onlyFileNameWithoutExt();
1343 boost::scoped_ptr<TempFile>
1344 tempfile(new TempFile(fileName().onlyPath(),
1345 justname + "-XXXXXX.lyx"));
1346 bool const symlink = fileName().isSymLink();
1348 tempfile->setAutoRemove(false);
1350 FileName savefile(tempfile->name());
1351 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1352 if (!writeFile(savefile))
1355 // we will set this to false if we fail
1356 bool made_backup = true;
1358 FileName backupName(absFileName() + '~');
1359 if (lyxrc.make_backup) {
1360 if (!lyxrc.backupdir_path.empty()) {
1361 string const mangledName =
1362 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1363 backupName = FileName(addName(lyxrc.backupdir_path,
1367 LYXERR(Debug::FILES, "Backing up original file to " <<
1368 backupName.absFileName());
1369 // Except file is symlink do not copy because of #6587.
1370 // Hard links have bad luck.
1371 made_backup = symlink ?
1372 fileName().copyTo(backupName):
1373 fileName().moveTo(backupName);
1376 Alert::error(_("Backup failure"),
1377 bformat(_("Cannot create backup file %1$s.\n"
1378 "Please check whether the directory exists and is writable."),
1379 from_utf8(backupName.absFileName())));
1380 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1384 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1385 // Only do this if tempfile is not in autoremove mode
1388 // If we have no symlink, we can simply rename the temp file.
1389 // Otherwise, we need to copy it so the symlink stays intact.
1390 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1391 savefile.moveTo(fileName()))
1393 // saveCheckSum() was already called by writeFile(), but the
1394 // time stamp is invalidated by copying/moving
1399 // else we saved the file, but failed to move it to the right location.
1401 if (lyxrc.make_backup && made_backup && !symlink) {
1402 // the original file was moved to filename.lyx~, so it will look
1403 // to the user as if it was deleted. (see bug #9234.) we could try
1404 // to restore it, but that would basically mean trying to do again
1405 // what we just failed to do. better to leave things as they are.
1406 Alert::error(_("Write failure"),
1407 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1408 "But LyX could not move it to:\n %2$s.\n"
1409 "Your original file has been backed up to:\n %3$s"),
1410 from_utf8(savefile.absFileName()),
1411 from_utf8(fileName().absFileName()),
1412 from_utf8(backupName.absFileName())));
1414 // either we did not try to make a backup, or else we tried and failed,
1415 // or else the original file was a symlink, in which case it was copied,
1416 // not moved. so the original file is intact.
1417 Alert::error(_("Write failure"),
1418 bformat(_("Cannot move saved file to:\n %1$s.\n"
1419 "But the file has successfully been saved as:\n %2$s."),
1420 from_utf8(fileName().absFileName()),
1421 from_utf8(savefile.absFileName())));
1427 bool Buffer::writeFile(FileName const & fname) const
1429 if (d->read_only && fname == d->filename)
1432 bool retval = false;
1434 docstring const str = bformat(_("Saving document %1$s..."),
1435 makeDisplayPath(fname.absFileName()));
1438 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1440 if (params().compressed) {
1441 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1442 retval = ofs && write(ofs);
1444 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1445 retval = ofs && write(ofs);
1449 message(str + _(" could not write file!"));
1454 // removeAutosaveFile();
1457 message(str + _(" done."));
1463 docstring Buffer::emergencyWrite()
1465 // No need to save if the buffer has not changed.
1469 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1471 docstring user_message = bformat(
1472 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1474 // We try to save three places:
1475 // 1) Same place as document. Unless it is an unnamed doc.
1477 string s = absFileName();
1480 if (writeFile(FileName(s))) {
1482 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1483 return user_message;
1485 user_message += " " + _("Save failed! Trying again...\n");
1489 // 2) In HOME directory.
1490 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1492 lyxerr << ' ' << s << endl;
1493 if (writeFile(FileName(s))) {
1495 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1496 return user_message;
1499 user_message += " " + _("Save failed! Trying yet again...\n");
1501 // 3) In "/tmp" directory.
1502 // MakeAbsPath to prepend the current
1503 // drive letter on OS/2
1504 s = addName(package().temp_dir().absFileName(), absFileName());
1506 lyxerr << ' ' << s << endl;
1507 if (writeFile(FileName(s))) {
1509 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1510 return user_message;
1513 user_message += " " + _("Save failed! Bummer. Document is lost.");
1516 return user_message;
1520 bool Buffer::write(ostream & ofs) const
1523 // Use the standard "C" locale for file output.
1524 ofs.imbue(locale::classic());
1527 // The top of the file should not be written by params().
1529 // write out a comment in the top of the file
1530 // Important: Keep the version formatting in sync with lyx2lyx and
1531 // tex2lyx (bug 7951)
1532 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1533 << " created this file. For more info see http://www.lyx.org/\n"
1534 << "\\lyxformat " << LYX_FORMAT << "\n"
1535 << "\\begin_document\n";
1537 /// For each author, set 'used' to true if there is a change
1538 /// by this author in the document; otherwise set it to 'false'.
1539 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1540 AuthorList::Authors::const_iterator a_end = params().authors().end();
1541 for (; a_it != a_end; ++a_it)
1542 a_it->setUsed(false);
1544 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1545 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1546 for ( ; it != end; ++it)
1547 it->checkAuthors(params().authors());
1549 // now write out the buffer parameters.
1550 ofs << "\\begin_header\n";
1551 params().writeFile(ofs, this);
1552 ofs << "\\end_header\n";
1555 ofs << "\n\\begin_body\n";
1557 ofs << "\n\\end_body\n";
1559 // Write marker that shows file is complete
1560 ofs << "\\end_document" << endl;
1562 // Shouldn't really be needed....
1565 // how to check if close went ok?
1566 // Following is an attempt... (BE 20001011)
1568 // good() returns false if any error occurred, including some
1569 // formatting error.
1570 // bad() returns true if something bad happened in the buffer,
1571 // which should include file system full errors.
1576 lyxerr << "File was not closed properly." << endl;
1583 bool Buffer::makeLaTeXFile(FileName const & fname,
1584 string const & original_path,
1585 OutputParams const & runparams_in,
1586 OutputWhat output) const
1588 OutputParams runparams = runparams_in;
1590 // This is necessary for LuaTeX/XeTeX with tex fonts.
1591 // See FIXME in BufferParams::encoding()
1592 if (runparams.isFullUnicode())
1593 runparams.encoding = encodings.fromLyXName("utf8-plain");
1595 string const encoding = runparams.encoding->iconvName();
1596 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1599 try { ofs.reset(encoding); }
1600 catch (iconv_codecvt_facet_exception const & e) {
1601 lyxerr << "Caught iconv exception: " << e.what() << endl;
1602 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1603 "verify that the support software for your encoding (%1$s) is "
1604 "properly installed"), from_ascii(encoding)));
1607 if (!openFileWrite(ofs, fname))
1610 ErrorList & errorList = d->errorLists["Export"];
1612 bool failed_export = false;
1613 otexstream os(ofs, d->texrow);
1615 // make sure we are ready to export
1616 // this needs to be done before we validate
1617 // FIXME Do we need to do this all the time? I.e., in children
1618 // of a master we are exporting?
1620 updateMacroInstances(OutputUpdate);
1623 os.texrow().reset();
1624 writeLaTeXSource(os, original_path, runparams, output);
1626 catch (EncodingException const & e) {
1627 docstring const failed(1, e.failed_char);
1629 oss << "0x" << hex << e.failed_char << dec;
1630 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1631 " (code point %2$s)"),
1632 failed, from_utf8(oss.str()));
1633 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1634 "representable in the chosen encoding.\n"
1635 "Changing the document encoding to utf8 could help."),
1636 e.par_id, e.pos, e.pos + 1));
1637 failed_export = true;
1639 catch (iconv_codecvt_facet_exception const & e) {
1640 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1641 _(e.what()), -1, 0, 0));
1642 failed_export = true;
1644 catch (exception const & e) {
1645 errorList.push_back(ErrorItem(_("conversion failed"),
1646 _(e.what()), -1, 0, 0));
1647 failed_export = true;
1650 lyxerr << "Caught some really weird exception..." << endl;
1656 failed_export = true;
1657 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1660 if (runparams_in.silent)
1664 return !failed_export;
1668 void Buffer::writeLaTeXSource(otexstream & os,
1669 string const & original_path,
1670 OutputParams const & runparams_in,
1671 OutputWhat output) const
1673 // The child documents, if any, shall be already loaded at this point.
1675 OutputParams runparams = runparams_in;
1677 // This is necessary for LuaTeX/XeTeX with tex fonts.
1678 // See FIXME in BufferParams::encoding()
1679 if (runparams.isFullUnicode())
1680 runparams.encoding = encodings.fromLyXName("utf8-plain");
1682 // If we are compiling a file standalone, even if this is the
1683 // child of some other buffer, let's cut the link here, so the
1684 // file is really independent and no concurring settings from
1685 // the master (e.g. branch state) interfere (see #8100).
1686 if (!runparams.is_child)
1687 d->ignore_parent = true;
1689 // Classify the unicode characters appearing in math insets
1690 BufferEncodings::initUnicodeMath(*this);
1692 // validate the buffer.
1693 LYXERR(Debug::LATEX, " Validating buffer...");
1694 LaTeXFeatures features(*this, params(), runparams);
1696 // This is only set once per document (in master)
1697 if (!runparams.is_child)
1698 runparams.use_polyglossia = features.usePolyglossia();
1699 LYXERR(Debug::LATEX, " Buffer validation done.");
1701 bool const output_preamble =
1702 output == FullSource || output == OnlyPreamble;
1703 bool const output_body =
1704 output == FullSource || output == OnlyBody;
1706 // The starting paragraph of the coming rows is the
1707 // first paragraph of the document. (Asger)
1708 if (output_preamble && runparams.nice) {
1709 os << "%% LyX " << lyx_version << " created this file. "
1710 "For more info, see http://www.lyx.org/.\n"
1711 "%% Do not edit unless you really know what "
1714 LYXERR(Debug::INFO, "lyx document header finished");
1716 // There are a few differences between nice LaTeX and usual files:
1717 // usual files have \batchmode and special input@path to allow
1718 // inclusion of figures specified by an explicitly relative path
1719 // (i.e., a path starting with './' or '../') with either \input or
1720 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1721 // input@path is set when the actual parameter original_path is set.
1722 // This is done for usual tex-file, but not for nice-latex-file.
1723 // (Matthias 250696)
1724 // Note that input@path is only needed for something the user does
1725 // in the preamble, included .tex files or ERT, files included by
1726 // LyX work without it.
1727 if (output_preamble) {
1728 if (!runparams.nice) {
1729 // code for usual, NOT nice-latex-file
1730 os << "\\batchmode\n"; // changed from \nonstopmode
1732 if (!original_path.empty()) {
1734 // We don't know the encoding of inputpath
1735 docstring const inputpath = from_utf8(original_path);
1736 docstring uncodable_glyphs;
1737 Encoding const * const enc = runparams.encoding;
1739 for (size_t n = 0; n < inputpath.size(); ++n) {
1740 if (!enc->encodable(inputpath[n])) {
1741 docstring const glyph(1, inputpath[n]);
1742 LYXERR0("Uncodable character '"
1744 << "' in input path!");
1745 uncodable_glyphs += glyph;
1750 // warn user if we found uncodable glyphs.
1751 if (!uncodable_glyphs.empty()) {
1752 frontend::Alert::warning(
1753 _("Uncodable character in file path"),
1755 _("The path of your document\n"
1757 "contains glyphs that are unknown "
1758 "in the current document encoding "
1759 "(namely %2$s). This may result in "
1760 "incomplete output, unless "
1761 "TEXINPUTS contains the document "
1762 "directory and you don't use "
1763 "explicitly relative paths (i.e., "
1764 "paths starting with './' or "
1765 "'../') in the preamble or in ERT."
1766 "\n\nIn case of problems, choose "
1767 "an appropriate document encoding\n"
1768 "(such as utf8) or change the "
1770 inputpath, uncodable_glyphs));
1773 support::latex_path(original_path);
1774 if (contains(docdir, '#')) {
1775 docdir = subst(docdir, "#", "\\#");
1776 os << "\\catcode`\\#=11"
1777 "\\def\\#{#}\\catcode`\\#=6\n";
1779 if (contains(docdir, '%')) {
1780 docdir = subst(docdir, "%", "\\%");
1781 os << "\\catcode`\\%=11"
1782 "\\def\\%{%}\\catcode`\\%=14\n";
1784 os << "\\makeatletter\n"
1785 << "\\def\\input@path{{"
1786 << docdir << "/}}\n"
1787 << "\\makeatother\n";
1791 // get parent macros (if this buffer has a parent) which will be
1792 // written at the document begin further down.
1793 MacroSet parentMacros;
1794 listParentMacros(parentMacros, features);
1796 // Write the preamble
1797 runparams.use_babel = params().writeLaTeX(os, features,
1798 d->filename.onlyPath());
1800 // Japanese might be required only in some children of a document,
1801 // but once required, we must keep use_japanese true.
1802 runparams.use_japanese |= features.isRequired("japanese");
1805 // Restore the parenthood if needed
1806 if (!runparams.is_child)
1807 d->ignore_parent = false;
1812 os << "\\begin{document}\n";
1814 // output the parent macros
1815 MacroSet::iterator it = parentMacros.begin();
1816 MacroSet::iterator end = parentMacros.end();
1817 for (; it != end; ++it) {
1818 int num_lines = (*it)->write(os.os(), true);
1819 os.texrow().newlines(num_lines);
1822 } // output_preamble
1824 os.texrow().start(paragraphs().begin()->id(), 0);
1826 LYXERR(Debug::INFO, "preamble finished, now the body.");
1829 latexParagraphs(*this, text(), os, runparams);
1831 // Restore the parenthood if needed
1832 if (!runparams.is_child)
1833 d->ignore_parent = false;
1835 // add this just in case after all the paragraphs
1838 if (output_preamble) {
1839 os << "\\end{document}\n";
1840 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1842 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1844 runparams_in.encoding = runparams.encoding;
1846 // Just to be sure. (Asger)
1847 os.texrow().newline();
1849 //for (int i = 0; i<d->texrow.rows(); i++) {
1851 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1852 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1855 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1856 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1860 void Buffer::makeDocBookFile(FileName const & fname,
1861 OutputParams const & runparams,
1862 OutputWhat output) const
1864 LYXERR(Debug::LATEX, "makeDocBookFile...");
1867 if (!openFileWrite(ofs, fname))
1870 // make sure we are ready to export
1871 // this needs to be done before we validate
1873 updateMacroInstances(OutputUpdate);
1875 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1879 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1883 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1884 OutputParams const & runparams,
1885 OutputWhat output) const
1887 LaTeXFeatures features(*this, params(), runparams);
1892 DocumentClass const & tclass = params().documentClass();
1893 string const & top_element = tclass.latexname();
1895 bool const output_preamble =
1896 output == FullSource || output == OnlyPreamble;
1897 bool const output_body =
1898 output == FullSource || output == OnlyBody;
1900 if (output_preamble) {
1901 if (runparams.flavor == OutputParams::XML)
1902 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1905 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1908 if (! tclass.class_header().empty())
1909 os << from_ascii(tclass.class_header());
1910 else if (runparams.flavor == OutputParams::XML)
1911 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1912 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1914 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1916 docstring preamble = from_utf8(params().preamble);
1917 if (runparams.flavor != OutputParams::XML ) {
1918 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1919 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1920 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1921 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1924 string const name = runparams.nice
1925 ? changeExtension(absFileName(), ".sgml") : fname;
1926 preamble += features.getIncludedFiles(name);
1927 preamble += features.getLyXSGMLEntities();
1929 if (!preamble.empty()) {
1930 os << "\n [ " << preamble << " ]";
1936 string top = top_element;
1938 if (runparams.flavor == OutputParams::XML)
1939 top += params().language->code();
1941 top += params().language->code().substr(0, 2);
1944 if (!params().options.empty()) {
1946 top += params().options;
1949 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1950 << " file was created by LyX " << lyx_version
1951 << "\n See http://www.lyx.org/ for more information -->\n";
1953 params().documentClass().counters().reset();
1955 sgml::openTag(os, top);
1957 docbookParagraphs(text(), *this, os, runparams);
1958 sgml::closeTag(os, top_element);
1963 void Buffer::makeLyXHTMLFile(FileName const & fname,
1964 OutputParams const & runparams) const
1966 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1969 if (!openFileWrite(ofs, fname))
1972 // make sure we are ready to export
1973 // this has to be done before we validate
1974 updateBuffer(UpdateMaster, OutputUpdate);
1975 updateMacroInstances(OutputUpdate);
1977 writeLyXHTMLSource(ofs, runparams, FullSource);
1981 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1985 void Buffer::writeLyXHTMLSource(odocstream & os,
1986 OutputParams const & runparams,
1987 OutputWhat output) const
1989 LaTeXFeatures features(*this, params(), runparams);
1991 d->bibinfo_.makeCitationLabels(*this);
1993 bool const output_preamble =
1994 output == FullSource || output == OnlyPreamble;
1995 bool const output_body =
1996 output == FullSource || output == OnlyBody || output == IncludedFile;
1998 if (output_preamble) {
1999 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2000 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
2001 // FIXME Language should be set properly.
2002 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2004 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2005 // FIXME Presumably need to set this right
2006 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2008 docstring const & doctitle = features.htmlTitle();
2010 << (doctitle.empty() ?
2011 from_ascii("LyX Document") :
2012 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2015 docstring styles = features.getTClassHTMLPreamble();
2016 if (!styles.empty())
2017 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2019 styles = from_utf8(features.getPreambleSnippets());
2020 if (!styles.empty())
2021 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2023 // we will collect CSS information in a stream, and then output it
2024 // either here, as part of the header, or else in a separate file.
2025 odocstringstream css;
2026 styles = from_utf8(features.getCSSSnippets());
2027 if (!styles.empty())
2028 css << "/* LyX Provided Styles */\n" << styles << '\n';
2030 styles = features.getTClassHTMLStyles();
2031 if (!styles.empty())
2032 css << "/* Layout-provided Styles */\n" << styles << '\n';
2034 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2035 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2036 if (needfg || needbg) {
2037 css << "\nbody {\n";
2040 << from_ascii(X11hexname(params().fontcolor))
2043 css << " background-color: "
2044 << from_ascii(X11hexname(params().backgroundcolor))
2049 docstring const dstyles = css.str();
2050 if (!dstyles.empty()) {
2051 bool written = false;
2052 if (params().html_css_as_file) {
2053 // open a file for CSS info
2055 string const fcssname = addName(temppath(), "docstyle.css");
2056 FileName const fcssfile = FileName(fcssname);
2057 if (openFileWrite(ocss, fcssfile)) {
2061 // write link to header
2062 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2064 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2067 // we are here if the CSS is supposed to be written to the header
2068 // or if we failed to write it to an external file.
2070 os << "<style type='text/css'>\n"
2079 bool const output_body_tag = (output != IncludedFile);
2080 if (output_body_tag)
2083 if (output != IncludedFile)
2084 // if we're an included file, the counters are in the master.
2085 params().documentClass().counters().reset();
2086 xhtmlParagraphs(text(), *this, xs, runparams);
2087 if (output_body_tag)
2091 if (output_preamble)
2096 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2097 // Other flags: -wall -v0 -x
2098 int Buffer::runChktex()
2102 // get LaTeX-Filename
2103 FileName const path(temppath());
2104 string const name = addName(path.absFileName(), latexName());
2105 string const org_path = filePath();
2107 PathChanger p(path); // path to LaTeX file
2108 message(_("Running chktex..."));
2110 // Generate the LaTeX file if neccessary
2111 OutputParams runparams(¶ms().encoding());
2112 runparams.flavor = OutputParams::LATEX;
2113 runparams.nice = false;
2114 runparams.linelen = lyxrc.plaintext_linelen;
2115 makeLaTeXFile(FileName(name), org_path, runparams);
2118 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2119 int const res = chktex.run(terr); // run chktex
2122 Alert::error(_("chktex failure"),
2123 _("Could not run chktex successfully."));
2125 ErrorList & errlist = d->errorLists["ChkTeX"];
2127 bufferErrors(terr, errlist);
2132 if (runparams.silent)
2133 d->errorLists["ChkTeX"].clear();
2141 void Buffer::validate(LaTeXFeatures & features) const
2143 // Validate the buffer params, but not for included
2144 // files, since they also use the parent buffer's
2146 if (!features.runparams().is_child)
2147 params().validate(features);
2149 for_each(paragraphs().begin(), paragraphs().end(),
2150 bind(&Paragraph::validate, _1, ref(features)));
2152 if (lyxerr.debugging(Debug::LATEX)) {
2153 features.showStruct();
2158 void Buffer::getLabelList(vector<docstring> & list) const
2160 // If this is a child document, use the master's list instead.
2162 masterBuffer()->getLabelList(list);
2167 Toc & toc = d->toc_backend.toc("label");
2168 TocIterator toc_it = toc.begin();
2169 TocIterator end = toc.end();
2170 for (; toc_it != end; ++toc_it) {
2171 if (toc_it->depth() == 0)
2172 list.push_back(toc_it->str());
2177 void Buffer::updateBibfilesCache(UpdateScope scope) const
2179 // FIXME This is probably unnecssary, given where we call this.
2180 // If this is a child document, use the parent's cache instead.
2181 if (parent() && scope != UpdateChildOnly) {
2182 masterBuffer()->updateBibfilesCache();
2186 d->bibfiles_cache_.clear();
2187 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2188 if (it->lyxCode() == BIBTEX_CODE) {
2189 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2190 support::FileNameList const bibfiles = inset.getBibFiles();
2191 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2194 } else if (it->lyxCode() == INCLUDE_CODE) {
2195 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2196 Buffer const * const incbuf = inset.getChildBuffer();
2199 support::FileNameList const & bibfiles =
2200 incbuf->getBibfilesCache(UpdateChildOnly);
2201 if (!bibfiles.empty()) {
2202 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2208 d->bibfile_cache_valid_ = true;
2209 d->bibinfo_cache_valid_ = false;
2210 d->cite_labels_valid_ = false;
2214 void Buffer::invalidateBibinfoCache() const
2216 d->bibinfo_cache_valid_ = false;
2217 d->cite_labels_valid_ = false;
2218 // also invalidate the cache for the parent buffer
2219 Buffer const * const pbuf = d->parent();
2221 pbuf->invalidateBibinfoCache();
2225 void Buffer::invalidateBibfileCache() const
2227 d->bibfile_cache_valid_ = false;
2228 d->bibinfo_cache_valid_ = false;
2229 d->cite_labels_valid_ = false;
2230 // also invalidate the cache for the parent buffer
2231 Buffer const * const pbuf = d->parent();
2233 pbuf->invalidateBibfileCache();
2237 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2239 // FIXME This is probably unnecessary, given where we call this.
2240 // If this is a child document, use the master's cache instead.
2241 Buffer const * const pbuf = masterBuffer();
2242 if (pbuf != this && scope != UpdateChildOnly)
2243 return pbuf->getBibfilesCache();
2245 if (!d->bibfile_cache_valid_)
2246 this->updateBibfilesCache(scope);
2248 return d->bibfiles_cache_;
2252 BiblioInfo const & Buffer::masterBibInfo() const
2254 Buffer const * const tmp = masterBuffer();
2256 return tmp->masterBibInfo();
2261 void Buffer::checkIfBibInfoCacheIsValid() const
2263 // use the master's cache
2264 Buffer const * const tmp = masterBuffer();
2266 tmp->checkIfBibInfoCacheIsValid();
2270 // compare the cached timestamps with the actual ones.
2271 FileNameList const & bibfiles_cache = getBibfilesCache();
2272 FileNameList::const_iterator ei = bibfiles_cache.begin();
2273 FileNameList::const_iterator en = bibfiles_cache.end();
2274 for (; ei != en; ++ ei) {
2275 time_t lastw = ei->lastModified();
2276 time_t prevw = d->bibfile_status_[*ei];
2277 if (lastw != prevw) {
2278 d->bibinfo_cache_valid_ = false;
2279 d->cite_labels_valid_ = false;
2280 d->bibfile_status_[*ei] = lastw;
2286 void Buffer::reloadBibInfoCache() const
2288 // use the master's cache
2289 Buffer const * const tmp = masterBuffer();
2291 tmp->reloadBibInfoCache();
2295 checkIfBibInfoCacheIsValid();
2296 if (d->bibinfo_cache_valid_)
2299 d->bibinfo_.clear();
2301 d->bibinfo_cache_valid_ = true;
2305 void Buffer::collectBibKeys() const
2307 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2308 it->collectBibKeys(it);
2312 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2314 Buffer const * tmp = masterBuffer();
2315 BiblioInfo & masterbi = (tmp == this) ?
2316 d->bibinfo_ : tmp->d->bibinfo_;
2317 masterbi.mergeBiblioInfo(bi);
2321 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2323 Buffer const * tmp = masterBuffer();
2324 BiblioInfo & masterbi = (tmp == this) ?
2325 d->bibinfo_ : tmp->d->bibinfo_;
2330 void Buffer::makeCitationLabels() const
2332 Buffer const * const master = masterBuffer();
2333 return d->bibinfo_.makeCitationLabels(*master);
2337 bool Buffer::citeLabelsValid() const
2339 return masterBuffer()->d->cite_labels_valid_;
2343 void Buffer::removeBiblioTempFiles() const
2345 // We remove files that contain LaTeX commands specific to the
2346 // particular bibliographic style being used, in order to avoid
2347 // LaTeX errors when we switch style.
2348 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2349 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2350 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2351 aux_file.removeFile();
2352 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2353 bbl_file.removeFile();
2354 // Also for the parent buffer
2355 Buffer const * const pbuf = parent();
2357 pbuf->removeBiblioTempFiles();
2361 bool Buffer::isDepClean(string const & name) const
2363 DepClean::const_iterator const it = d->dep_clean.find(name);
2364 if (it == d->dep_clean.end())
2370 void Buffer::markDepClean(string const & name)
2372 d->dep_clean[name] = true;
2376 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2379 // FIXME? if there is an Buffer LFUN that can be dispatched even
2380 // if internal, put a switch '(cmd.action)' here.
2386 switch (cmd.action()) {
2388 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2389 flag.setOnOff(isReadonly());
2392 // FIXME: There is need for a command-line import.
2393 //case LFUN_BUFFER_IMPORT:
2395 case LFUN_BUFFER_AUTO_SAVE:
2398 case LFUN_BUFFER_EXPORT_CUSTOM:
2399 // FIXME: Nothing to check here?
2402 case LFUN_BUFFER_EXPORT: {
2403 docstring const arg = cmd.argument();
2404 if (arg == "custom") {
2408 string format = to_utf8(arg);
2409 size_t pos = format.find(' ');
2410 if (pos != string::npos)
2411 format = format.substr(0, pos);
2412 enable = params().isExportable(format);
2414 flag.message(bformat(
2415 _("Don't know how to export to format: %1$s"), arg));
2419 case LFUN_BUFFER_CHKTEX:
2420 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2423 case LFUN_BUILD_PROGRAM:
2424 enable = params().isExportable("program");
2427 case LFUN_BRANCH_ACTIVATE:
2428 case LFUN_BRANCH_DEACTIVATE:
2429 case LFUN_BRANCH_MASTER_ACTIVATE:
2430 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2431 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2432 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2433 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2434 : params().branchlist();
2435 docstring const branchName = cmd.argument();
2436 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2440 case LFUN_BRANCH_ADD:
2441 case LFUN_BRANCHES_RENAME:
2442 case LFUN_BUFFER_PRINT:
2443 // if no Buffer is present, then of course we won't be called!
2446 case LFUN_BUFFER_LANGUAGE:
2447 enable = !isReadonly();
2450 case LFUN_BUFFER_VIEW_CACHE:
2451 enable = (d->preview_file_).exists();
2457 flag.setEnabled(enable);
2462 void Buffer::dispatch(string const & command, DispatchResult & result)
2464 return dispatch(lyxaction.lookupFunc(command), result);
2468 // NOTE We can end up here even if we have no GUI, because we are called
2469 // by LyX::exec to handled command-line requests. So we may need to check
2470 // whether we have a GUI or not. The boolean use_gui holds this information.
2471 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2474 // FIXME? if there is an Buffer LFUN that can be dispatched even
2475 // if internal, put a switch '(cmd.action())' here.
2476 dr.dispatched(false);
2479 string const argument = to_utf8(func.argument());
2480 // We'll set this back to false if need be.
2481 bool dispatched = true;
2482 undo().beginUndoGroup();
2484 switch (func.action()) {
2485 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2486 if (lyxvc().inUse()) {
2487 string log = lyxvc().toggleReadOnly();
2492 setReadonly(!isReadonly());
2495 case LFUN_BUFFER_EXPORT: {
2496 ExportStatus const status = doExport(argument, false);
2497 dr.setError(status != ExportSuccess);
2498 if (status != ExportSuccess)
2499 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2504 case LFUN_BUILD_PROGRAM: {
2505 ExportStatus const status = doExport("program", true);
2506 dr.setError(status != ExportSuccess);
2507 if (status != ExportSuccess)
2508 dr.setMessage(_("Error generating literate programming code."));
2512 case LFUN_BUFFER_CHKTEX:
2516 case LFUN_BUFFER_EXPORT_CUSTOM: {
2518 string command = split(argument, format_name, ' ');
2519 Format const * format = formats.getFormat(format_name);
2521 lyxerr << "Format \"" << format_name
2522 << "\" not recognized!"
2527 // The name of the file created by the conversion process
2530 // Output to filename
2531 if (format->name() == "lyx") {
2532 string const latexname = latexName(false);
2533 filename = changeExtension(latexname,
2534 format->extension());
2535 filename = addName(temppath(), filename);
2537 if (!writeFile(FileName(filename)))
2541 doExport(format_name, true, filename);
2544 // Substitute $$FName for filename
2545 if (!contains(command, "$$FName"))
2546 command = "( " + command + " ) < $$FName";
2547 command = subst(command, "$$FName", filename);
2549 // Execute the command in the background
2551 call.startscript(Systemcall::DontWait, command,
2552 filePath(), layoutPos());
2556 // FIXME: There is need for a command-line import.
2558 case LFUN_BUFFER_IMPORT:
2563 case LFUN_BUFFER_AUTO_SAVE:
2565 resetAutosaveTimers();
2568 case LFUN_BRANCH_ACTIVATE:
2569 case LFUN_BRANCH_DEACTIVATE:
2570 case LFUN_BRANCH_MASTER_ACTIVATE:
2571 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2572 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2573 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2574 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2577 docstring const branch_name = func.argument();
2578 // the case without a branch name is handled elsewhere
2579 if (branch_name.empty()) {
2583 Branch * branch = buf->params().branchlist().find(branch_name);
2585 LYXERR0("Branch " << branch_name << " does not exist.");
2587 docstring const msg =
2588 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2592 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2593 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2594 if (branch->isSelected() != activate) {
2595 buf->undo().recordUndoBufferParams(CursorData());
2596 branch->setSelected(activate);
2598 dr.screenUpdate(Update::Force);
2599 dr.forceBufferUpdate();
2604 case LFUN_BRANCH_ADD: {
2605 docstring branch_name = func.argument();
2606 if (branch_name.empty()) {
2610 BranchList & branch_list = params().branchlist();
2611 vector<docstring> const branches =
2612 getVectorFromString(branch_name, branch_list.separator());
2614 for (vector<docstring>::const_iterator it = branches.begin();
2615 it != branches.end(); ++it) {
2617 Branch * branch = branch_list.find(branch_name);
2619 LYXERR0("Branch " << branch_name << " already exists.");
2623 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2625 undo().recordUndoBufferParams(CursorData());
2626 branch_list.add(branch_name);
2627 branch = branch_list.find(branch_name);
2628 string const x11hexname = X11hexname(branch->color());
2629 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2630 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2632 dr.screenUpdate(Update::Force);
2640 case LFUN_BRANCHES_RENAME: {
2641 if (func.argument().empty())
2644 docstring const oldname = from_utf8(func.getArg(0));
2645 docstring const newname = from_utf8(func.getArg(1));
2646 InsetIterator it = inset_iterator_begin(inset());
2647 InsetIterator const end = inset_iterator_end(inset());
2648 bool success = false;
2649 for (; it != end; ++it) {
2650 if (it->lyxCode() == BRANCH_CODE) {
2651 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2652 if (ins.branch() == oldname) {
2653 undo().recordUndo(CursorData(it));
2654 ins.rename(newname);
2659 if (it->lyxCode() == INCLUDE_CODE) {
2660 // get buffer of external file
2661 InsetInclude const & ins =
2662 static_cast<InsetInclude const &>(*it);
2663 Buffer * child = ins.getChildBuffer();
2666 child->dispatch(func, dr);
2671 dr.screenUpdate(Update::Force);
2672 dr.forceBufferUpdate();
2677 case LFUN_BUFFER_PRINT: {
2678 // we'll assume there's a problem until we succeed
2680 string target = func.getArg(0);
2681 string target_name = func.getArg(1);
2682 string command = func.getArg(2);
2685 || target_name.empty()
2686 || command.empty()) {
2687 LYXERR0("Unable to parse " << func.argument());
2688 docstring const msg =
2689 bformat(_("Unable to parse \"%1$s\""), func.argument());
2693 if (target != "printer" && target != "file") {
2694 LYXERR0("Unrecognized target \"" << target << '"');
2695 docstring const msg =
2696 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2701 if (doExport("dvi", true) != ExportSuccess) {
2702 showPrintError(absFileName());
2703 dr.setMessage(_("Error exporting to DVI."));
2707 // Push directory path.
2708 string const path = temppath();
2709 // Prevent the compiler from optimizing away p
2713 // there are three cases here:
2714 // 1. we print to a file
2715 // 2. we print directly to a printer
2716 // 3. we print using a spool command (print to file first)
2719 string const dviname = changeExtension(latexName(true), "dvi");
2721 if (target == "printer") {
2722 if (!lyxrc.print_spool_command.empty()) {
2723 // case 3: print using a spool
2724 string const psname = changeExtension(dviname,".ps");
2725 command += ' ' + lyxrc.print_to_file
2728 + quoteName(dviname);
2730 string command2 = lyxrc.print_spool_command + ' ';
2731 if (target_name != "default") {
2732 command2 += lyxrc.print_spool_printerprefix
2736 command2 += quoteName(psname);
2738 // If successful, then spool command
2739 res = one.startscript(Systemcall::Wait, command,
2740 filePath(), layoutPos());
2743 // If there's no GUI, we have to wait on this command. Otherwise,
2744 // LyX deletes the temporary directory, and with it the spooled
2745 // file, before it can be printed!!
2746 Systemcall::Starttype stype = use_gui ?
2747 Systemcall::DontWait : Systemcall::Wait;
2748 res = one.startscript(stype, command2,
2753 // case 2: print directly to a printer
2754 if (target_name != "default")
2755 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2757 Systemcall::Starttype stype = use_gui ?
2758 Systemcall::DontWait : Systemcall::Wait;
2759 res = one.startscript(stype,
2760 command + quoteName(dviname),
2761 filePath(), layoutPos());
2765 // case 1: print to a file
2766 FileName const filename(makeAbsPath(target_name, filePath()));
2767 FileName const dvifile(makeAbsPath(dviname, path));
2768 if (filename.exists()) {
2769 docstring text = bformat(
2770 _("The file %1$s already exists.\n\n"
2771 "Do you want to overwrite that file?"),
2772 makeDisplayPath(filename.absFileName()));
2773 if (Alert::prompt(_("Overwrite file?"),
2774 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2777 command += ' ' + lyxrc.print_to_file
2778 + quoteName(filename.toFilesystemEncoding())
2780 + quoteName(dvifile.toFilesystemEncoding());
2782 Systemcall::Starttype stype = use_gui ?
2783 Systemcall::DontWait : Systemcall::Wait;
2784 res = one.startscript(stype, command, filePath(), layoutPos());
2790 dr.setMessage(_("Error running external commands."));
2791 showPrintError(absFileName());
2796 case LFUN_BUFFER_VIEW_CACHE:
2797 if (!formats.view(*this, d->preview_file_,
2798 d->preview_format_))
2799 dr.setMessage(_("Error viewing the output file."));
2806 dr.dispatched(dispatched);
2807 undo().endUndoGroup();
2811 void Buffer::changeLanguage(Language const * from, Language const * to)
2813 LASSERT(from, return);
2814 LASSERT(to, return);
2816 for_each(par_iterator_begin(),
2818 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2822 bool Buffer::isMultiLingual() const
2824 ParConstIterator end = par_iterator_end();
2825 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2826 if (it->isMultiLingual(params()))
2833 std::set<Language const *> Buffer::getLanguages() const
2835 std::set<Language const *> languages;
2836 getLanguages(languages);
2841 void Buffer::getLanguages(std::set<Language const *> & languages) const
2843 ParConstIterator end = par_iterator_end();
2844 // add the buffer language, even if it's not actively used
2845 languages.insert(language());
2846 // iterate over the paragraphs
2847 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2848 it->getLanguages(languages);
2850 ListOfBuffers clist = getDescendents();
2851 ListOfBuffers::const_iterator cit = clist.begin();
2852 ListOfBuffers::const_iterator const cen = clist.end();
2853 for (; cit != cen; ++cit)
2854 (*cit)->getLanguages(languages);
2858 DocIterator Buffer::getParFromID(int const id) const
2860 Buffer * buf = const_cast<Buffer *>(this);
2862 // John says this is called with id == -1 from undo
2863 lyxerr << "getParFromID(), id: " << id << endl;
2864 return doc_iterator_end(buf);
2867 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2868 if (it.paragraph().id() == id)
2871 return doc_iterator_end(buf);
2875 bool Buffer::hasParWithID(int const id) const
2877 return !getParFromID(id).atEnd();
2881 ParIterator Buffer::par_iterator_begin()
2883 return ParIterator(doc_iterator_begin(this));
2887 ParIterator Buffer::par_iterator_end()
2889 return ParIterator(doc_iterator_end(this));
2893 ParConstIterator Buffer::par_iterator_begin() const
2895 return ParConstIterator(doc_iterator_begin(this));
2899 ParConstIterator Buffer::par_iterator_end() const
2901 return ParConstIterator(doc_iterator_end(this));
2905 Language const * Buffer::language() const
2907 return params().language;
2911 docstring const Buffer::B_(string const & l10n) const
2913 return params().B_(l10n);
2917 bool Buffer::isClean() const
2919 return d->lyx_clean;
2923 bool Buffer::isExternallyModified(CheckMethod method) const
2925 LASSERT(d->filename.exists(), return false);
2926 // if method == timestamp, check timestamp before checksum
2927 return (method == checksum_method
2928 || d->timestamp_ != d->filename.lastModified())
2929 && d->checksum_ != d->filename.checksum();
2933 void Buffer::saveCheckSum() const
2935 FileName const & file = d->filename;
2938 if (file.exists()) {
2939 d->timestamp_ = file.lastModified();
2940 d->checksum_ = file.checksum();
2942 // in the case of save to a new file.
2949 void Buffer::markClean() const
2951 if (!d->lyx_clean) {
2952 d->lyx_clean = true;
2955 // if the .lyx file has been saved, we don't need an
2957 d->bak_clean = true;
2958 d->undo_.markDirty();
2962 void Buffer::setUnnamed(bool flag)
2968 bool Buffer::isUnnamed() const
2975 /// Don't check unnamed, here: isInternal() is used in
2976 /// newBuffer(), where the unnamed flag has not been set by anyone
2977 /// yet. Also, for an internal buffer, there should be no need for
2978 /// retrieving fileName() nor for checking if it is unnamed or not.
2979 bool Buffer::isInternal() const
2981 return d->internal_buffer;
2985 void Buffer::setInternal(bool flag)
2987 d->internal_buffer = flag;
2991 void Buffer::markDirty()
2994 d->lyx_clean = false;
2997 d->bak_clean = false;
2999 DepClean::iterator it = d->dep_clean.begin();
3000 DepClean::const_iterator const end = d->dep_clean.end();
3002 for (; it != end; ++it)
3007 FileName Buffer::fileName() const
3013 string Buffer::absFileName() const
3015 return d->filename.absFileName();
3019 string Buffer::filePath() const
3021 string const abs = d->filename.onlyPath().absFileName();
3024 int last = abs.length() - 1;
3026 return abs[last] == '/' ? abs : abs + '/';
3030 string Buffer::layoutPos() const
3032 return d->layout_position;
3036 void Buffer::setLayoutPos(string const & path)
3039 d->layout_position.clear();
3043 LATTEST(FileName::isAbsolute(path));
3045 d->layout_position =
3046 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3048 if (d->layout_position.empty())
3049 d->layout_position = ".";
3053 bool Buffer::isReadonly() const
3055 return d->read_only;
3059 void Buffer::setParent(Buffer const * buffer)
3061 // Avoids recursive include.
3062 d->setParent(buffer == this ? 0 : buffer);
3067 Buffer const * Buffer::parent() const
3073 ListOfBuffers Buffer::allRelatives() const
3075 ListOfBuffers lb = masterBuffer()->getDescendents();
3076 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3081 Buffer const * Buffer::masterBuffer() const
3083 // FIXME Should be make sure we are not in some kind
3084 // of recursive include? A -> B -> A will crash this.
3085 Buffer const * const pbuf = d->parent();
3089 return pbuf->masterBuffer();
3093 bool Buffer::isChild(Buffer * child) const
3095 return d->children_positions.find(child) != d->children_positions.end();
3099 DocIterator Buffer::firstChildPosition(Buffer const * child)
3101 Impl::BufferPositionMap::iterator it;
3102 it = d->children_positions.find(child);
3103 if (it == d->children_positions.end())
3104 return DocIterator(this);
3109 bool Buffer::hasChildren() const
3111 return !d->children_positions.empty();
3115 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3117 // loop over children
3118 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3119 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3120 for (; it != end; ++it) {
3121 Buffer * child = const_cast<Buffer *>(it->first);
3123 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3124 if (bit != clist.end())
3126 clist.push_back(child);
3128 // there might be grandchildren
3129 child->collectChildren(clist, true);
3134 ListOfBuffers Buffer::getChildren() const
3137 collectChildren(v, false);
3138 // Make sure we have not included ourselves.
3139 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3140 if (bit != v.end()) {
3141 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3148 ListOfBuffers Buffer::getDescendents() const
3151 collectChildren(v, true);
3152 // Make sure we have not included ourselves.
3153 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3154 if (bit != v.end()) {
3155 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3162 template<typename M>
3163 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3168 typename M::const_iterator it = m.lower_bound(x);
3169 if (it == m.begin())
3177 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3178 DocIterator const & pos) const
3180 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3182 // if paragraphs have no macro context set, pos will be empty
3186 // we haven't found anything yet
3187 DocIterator bestPos = owner_->par_iterator_begin();
3188 MacroData const * bestData = 0;
3190 // find macro definitions for name
3191 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3192 if (nameIt != macros.end()) {
3193 // find last definition in front of pos or at pos itself
3194 PositionScopeMacroMap::const_iterator it
3195 = greatest_below(nameIt->second, pos);
3196 if (it != nameIt->second.end()) {
3198 // scope ends behind pos?
3199 if (pos < it->second.scope) {
3200 // Looks good, remember this. If there
3201 // is no external macro behind this,
3202 // we found the right one already.
3203 bestPos = it->first;
3204 bestData = &it->second.macro;
3208 // try previous macro if there is one
3209 if (it == nameIt->second.begin())
3216 // find macros in included files
3217 PositionScopeBufferMap::const_iterator it
3218 = greatest_below(position_to_children, pos);
3219 if (it == position_to_children.end())
3220 // no children before
3224 // do we know something better (i.e. later) already?
3225 if (it->first < bestPos )
3228 // scope ends behind pos?
3229 if (pos < it->second.scope
3230 && (cloned_buffer_ ||
3231 theBufferList().isLoaded(it->second.buffer))) {
3232 // look for macro in external file
3234 MacroData const * data
3235 = it->second.buffer->getMacro(name, false);
3238 bestPos = it->first;
3244 // try previous file if there is one
3245 if (it == position_to_children.begin())
3250 // return the best macro we have found
3255 MacroData const * Buffer::getMacro(docstring const & name,
3256 DocIterator const & pos, bool global) const
3261 // query buffer macros
3262 MacroData const * data = d->getBufferMacro(name, pos);
3266 // If there is a master buffer, query that
3267 Buffer const * const pbuf = d->parent();
3269 d->macro_lock = true;
3270 MacroData const * macro = pbuf->getMacro(
3271 name, *this, false);
3272 d->macro_lock = false;
3278 data = MacroTable::globalMacros().get(name);
3287 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3289 // set scope end behind the last paragraph
3290 DocIterator scope = par_iterator_begin();
3291 scope.pit() = scope.lastpit() + 1;
3293 return getMacro(name, scope, global);
3297 MacroData const * Buffer::getMacro(docstring const & name,
3298 Buffer const & child, bool global) const
3300 // look where the child buffer is included first
3301 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3302 if (it == d->children_positions.end())
3305 // check for macros at the inclusion position
3306 return getMacro(name, it->second, global);
3310 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3312 pit_type const lastpit = it.lastpit();
3314 // look for macros in each paragraph
3315 while (it.pit() <= lastpit) {
3316 Paragraph & par = it.paragraph();
3318 // iterate over the insets of the current paragraph
3319 InsetList const & insets = par.insetList();
3320 InsetList::const_iterator iit = insets.begin();
3321 InsetList::const_iterator end = insets.end();
3322 for (; iit != end; ++iit) {
3323 it.pos() = iit->pos;
3325 // is it a nested text inset?
3326 if (iit->inset->asInsetText()) {
3327 // Inset needs its own scope?
3328 InsetText const * itext = iit->inset->asInsetText();
3329 bool newScope = itext->isMacroScope();
3331 // scope which ends just behind the inset
3332 DocIterator insetScope = it;
3335 // collect macros in inset
3336 it.push_back(CursorSlice(*iit->inset));
3337 updateMacros(it, newScope ? insetScope : scope);
3342 if (iit->inset->asInsetTabular()) {
3343 CursorSlice slice(*iit->inset);
3344 size_t const numcells = slice.nargs();
3345 for (; slice.idx() < numcells; slice.forwardIdx()) {
3346 it.push_back(slice);
3347 updateMacros(it, scope);
3353 // is it an external file?
3354 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3355 // get buffer of external file
3356 InsetInclude const & inset =
3357 static_cast<InsetInclude const &>(*iit->inset);
3359 Buffer * child = inset.getChildBuffer();
3364 // register its position, but only when it is
3365 // included first in the buffer
3366 if (children_positions.find(child) ==
3367 children_positions.end())
3368 children_positions[child] = it;
3370 // register child with its scope
3371 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3375 InsetMath * im = iit->inset->asInsetMath();
3376 if (doing_export && im) {
3377 InsetMathHull * hull = im->asHullInset();
3379 hull->recordLocation(it);
3382 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3386 MathMacroTemplate & macroTemplate =
3387 *iit->inset->asInsetMath()->asMacroTemplate();
3388 MacroContext mc(owner_, it);
3389 macroTemplate.updateToContext(mc);
3392 bool valid = macroTemplate.validMacro();
3393 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3394 // then the BufferView's cursor will be invalid in
3395 // some cases which leads to crashes.
3400 // FIXME (Abdel), I don't understand why we pass 'it' here
3401 // instead of 'macroTemplate' defined above... is this correct?
3402 macros[macroTemplate.name()][it] =
3403 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3413 void Buffer::updateMacros() const
3418 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3420 // start with empty table
3422 d->children_positions.clear();
3423 d->position_to_children.clear();
3425 // Iterate over buffer, starting with first paragraph
3426 // The scope must be bigger than any lookup DocIterator
3427 // later. For the global lookup, lastpit+1 is used, hence
3428 // we use lastpit+2 here.
3429 DocIterator it = par_iterator_begin();
3430 DocIterator outerScope = it;
3431 outerScope.pit() = outerScope.lastpit() + 2;
3432 d->updateMacros(it, outerScope);
3436 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3438 InsetIterator it = inset_iterator_begin(inset());
3439 InsetIterator const end = inset_iterator_end(inset());
3440 for (; it != end; ++it) {
3441 if (it->lyxCode() == BRANCH_CODE) {
3442 InsetBranch & br = static_cast<InsetBranch &>(*it);
3443 docstring const name = br.branch();
3444 if (!from_master && !params().branchlist().find(name))
3445 result.push_back(name);
3446 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3447 result.push_back(name);
3450 if (it->lyxCode() == INCLUDE_CODE) {
3451 // get buffer of external file
3452 InsetInclude const & ins =
3453 static_cast<InsetInclude const &>(*it);
3454 Buffer * child = ins.getChildBuffer();
3457 child->getUsedBranches(result, true);
3460 // remove duplicates
3465 void Buffer::updateMacroInstances(UpdateType utype) const
3467 LYXERR(Debug::MACROS, "updateMacroInstances for "
3468 << d->filename.onlyFileName());
3469 DocIterator it = doc_iterator_begin(this);
3471 DocIterator const end = doc_iterator_end(this);
3472 for (; it != end; it.forwardInset()) {
3473 // look for MathData cells in InsetMathNest insets
3474 InsetMath * minset = it.nextInset()->asInsetMath();
3478 // update macro in all cells of the InsetMathNest
3479 DocIterator::idx_type n = minset->nargs();
3480 MacroContext mc = MacroContext(this, it);
3481 for (DocIterator::idx_type i = 0; i < n; ++i) {
3482 MathData & data = minset->cell(i);
3483 data.updateMacros(0, mc, utype);
3489 void Buffer::listMacroNames(MacroNameSet & macros) const
3494 d->macro_lock = true;
3496 // loop over macro names
3497 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3498 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3499 for (; nameIt != nameEnd; ++nameIt)
3500 macros.insert(nameIt->first);
3502 // loop over children
3503 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3504 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3505 for (; it != end; ++it)
3506 it->first->listMacroNames(macros);
3509 Buffer const * const pbuf = d->parent();
3511 pbuf->listMacroNames(macros);
3513 d->macro_lock = false;
3517 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3519 Buffer const * const pbuf = d->parent();
3524 pbuf->listMacroNames(names);
3527 MacroNameSet::iterator it = names.begin();
3528 MacroNameSet::iterator end = names.end();
3529 for (; it != end; ++it) {
3531 MacroData const * data =
3532 pbuf->getMacro(*it, *this, false);
3534 macros.insert(data);
3536 // we cannot access the original MathMacroTemplate anymore
3537 // here to calls validate method. So we do its work here manually.
3538 // FIXME: somehow make the template accessible here.
3539 if (data->optionals() > 0)
3540 features.require("xargs");
3546 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3549 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3551 RefCache::iterator it = d->ref_cache_.find(label);
3552 if (it != d->ref_cache_.end())
3553 return it->second.second;
3555 static InsetLabel const * dummy_il = 0;
3556 static References const dummy_refs;
3557 it = d->ref_cache_.insert(
3558 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3559 return it->second.second;
3563 Buffer::References const & Buffer::references(docstring const & label) const
3565 return const_cast<Buffer *>(this)->getReferenceCache(label);
3569 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3571 References & refs = getReferenceCache(label);
3572 refs.push_back(make_pair(inset, it));
3576 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3578 masterBuffer()->d->ref_cache_[label].first = il;
3582 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3584 return masterBuffer()->d->ref_cache_[label].first;
3588 void Buffer::clearReferenceCache() const
3591 d->ref_cache_.clear();
3595 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3597 //FIXME: This does not work for child documents yet.
3598 reloadBibInfoCache();
3600 // Check if the label 'from' appears more than once
3601 BiblioInfo const & keys = masterBibInfo();
3602 BiblioInfo::const_iterator bit = keys.begin();
3603 BiblioInfo::const_iterator bend = keys.end();
3604 vector<docstring> labels;
3606 for (; bit != bend; ++bit)
3608 labels.push_back(bit->first);
3610 if (count(labels.begin(), labels.end(), from) > 1)
3613 string const paramName = "key";
3614 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3615 if (it->lyxCode() != CITE_CODE)
3617 InsetCommand * inset = it->asInsetCommand();
3618 docstring const oldValue = inset->getParam(paramName);
3619 if (oldValue == from)
3620 inset->setParam(paramName, to);
3625 void Buffer::getSourceCode(odocstream & os, string const & format,
3626 pit_type par_begin, pit_type par_end,
3627 OutputWhat output, bool master) const
3629 OutputParams runparams(¶ms().encoding());
3630 runparams.nice = true;
3631 runparams.flavor = params().getOutputFlavor(format);
3632 runparams.linelen = lyxrc.plaintext_linelen;
3633 // No side effect of file copying and image conversion
3634 runparams.dryrun = true;
3636 if (output == CurrentParagraph) {
3637 runparams.par_begin = par_begin;
3638 runparams.par_end = par_end;
3639 if (par_begin + 1 == par_end) {
3641 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3645 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3646 convert<docstring>(par_begin),
3647 convert<docstring>(par_end - 1))
3650 // output paragraphs
3651 if (runparams.flavor == OutputParams::LYX) {
3652 Paragraph const & par = text().paragraphs()[par_begin];
3654 depth_type dt = par.getDepth();
3655 par.write(ods, params(), dt);
3656 os << from_utf8(ods.str());
3657 } else if (runparams.flavor == OutputParams::HTML) {
3659 setMathFlavor(runparams);
3660 xhtmlParagraphs(text(), *this, xs, runparams);
3661 } else if (runparams.flavor == OutputParams::TEXT) {
3663 // FIXME Handles only one paragraph, unlike the others.
3664 // Probably should have some routine with a signature like them.
3665 writePlaintextParagraph(*this,
3666 text().paragraphs()[par_begin], os, runparams, dummy);
3667 } else if (params().isDocBook()) {
3668 docbookParagraphs(text(), *this, os, runparams);
3670 // If we are previewing a paragraph, even if this is the
3671 // child of some other buffer, let's cut the link here,
3672 // so that no concurring settings from the master
3673 // (e.g. branch state) interfere (see #8101).
3675 d->ignore_parent = true;
3676 // We need to validate the Buffer params' features here
3677 // in order to know if we should output polyglossia
3678 // macros (instead of babel macros)
3679 LaTeXFeatures features(*this, params(), runparams);
3680 params().validate(features);
3681 runparams.use_polyglossia = features.usePolyglossia();
3686 // latex or literate
3687 otexstream ots(os, texrow);
3690 latexParagraphs(*this, text(), ots, runparams);
3692 // Restore the parenthood
3694 d->ignore_parent = false;
3698 if (output == FullSource)
3699 os << _("Preview source code");
3700 else if (output == OnlyPreamble)
3701 os << _("Preview preamble");
3702 else if (output == OnlyBody)
3703 os << _("Preview body");
3705 if (runparams.flavor == OutputParams::LYX) {
3707 if (output == FullSource)
3709 else if (output == OnlyPreamble)
3710 params().writeFile(ods, this);
3711 else if (output == OnlyBody)
3713 os << from_utf8(ods.str());
3714 } else if (runparams.flavor == OutputParams::HTML) {
3715 writeLyXHTMLSource(os, runparams, output);
3716 } else if (runparams.flavor == OutputParams::TEXT) {
3717 if (output == OnlyPreamble) {
3718 os << "% "<< _("Plain text does not have a preamble.");
3720 writePlaintextFile(*this, os, runparams);
3721 } else if (params().isDocBook()) {
3722 writeDocBookSource(os, absFileName(), runparams, output);
3724 // latex or literate
3726 d->texrow.newline();
3727 d->texrow.newline();
3728 otexstream ots(os, d->texrow);
3730 runparams.is_child = true;
3731 writeLaTeXSource(ots, string(), runparams, output);
3737 ErrorList & Buffer::errorList(string const & type) const
3739 return d->errorLists[type];
3743 void Buffer::updateTocItem(std::string const & type,
3744 DocIterator const & dit) const
3747 d->gui_->updateTocItem(type, dit);
3751 void Buffer::structureChanged() const
3754 d->gui_->structureChanged();
3758 void Buffer::errors(string const & err, bool from_master) const
3761 d->gui_->errors(err, from_master);
3765 void Buffer::message(docstring const & msg) const
3768 d->gui_->message(msg);
3772 void Buffer::setBusy(bool on) const
3775 d->gui_->setBusy(on);
3779 void Buffer::updateTitles() const
3782 d->wa_->updateTitles();
3786 void Buffer::resetAutosaveTimers() const
3789 d->gui_->resetAutosaveTimers();
3793 bool Buffer::hasGuiDelegate() const
3799 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3808 class AutoSaveBuffer : public ForkedProcess {
3811 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3812 : buffer_(buffer), fname_(fname) {}
3814 virtual shared_ptr<ForkedProcess> clone() const
3816 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3821 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3822 from_utf8(fname_.absFileName())));
3823 return run(DontWait);
3827 virtual int generateChild();
3829 Buffer const & buffer_;
3834 int AutoSaveBuffer::generateChild()
3836 #if defined(__APPLE__)
3837 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3838 * We should use something else like threads.
3840 * Since I do not know how to determine at run time what is the OS X
3841 * version, I just disable forking altogether for now (JMarc)
3843 pid_t const pid = -1;
3845 // tmp_ret will be located (usually) in /tmp
3846 // will that be a problem?
3847 // Note that this calls ForkedCalls::fork(), so it's
3848 // ok cross-platform.
3849 pid_t const pid = fork();
3850 // If you want to debug the autosave
3851 // you should set pid to -1, and comment out the fork.
3852 if (pid != 0 && pid != -1)
3856 // pid = -1 signifies that lyx was unable
3857 // to fork. But we will do the save
3859 bool failed = false;
3860 TempFile tempfile("lyxautoXXXXXX.lyx");
3861 tempfile.setAutoRemove(false);
3862 FileName const tmp_ret = tempfile.name();
3863 if (!tmp_ret.empty()) {
3864 if (!buffer_.writeFile(tmp_ret))
3866 else if (!tmp_ret.moveTo(fname_))
3872 // failed to write/rename tmp_ret so try writing direct
3873 if (!buffer_.writeFile(fname_)) {
3874 // It is dangerous to do this in the child,
3875 // but safe in the parent, so...
3876 if (pid == -1) // emit message signal.
3877 buffer_.message(_("Autosave failed!"));
3881 if (pid == 0) // we are the child so...
3890 FileName Buffer::getEmergencyFileName() const
3892 return FileName(d->filename.absFileName() + ".emergency");
3896 FileName Buffer::getAutosaveFileName() const
3898 // if the document is unnamed try to save in the backup dir, else
3899 // in the default document path, and as a last try in the filePath,
3900 // which will most often be the temporary directory
3903 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3904 : lyxrc.backupdir_path;
3905 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3908 string const fname = "#" + d->filename.onlyFileName() + "#";
3910 return makeAbsPath(fname, fpath);
3914 void Buffer::removeAutosaveFile() const
3916 FileName const f = getAutosaveFileName();
3922 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3924 FileName const newauto = getAutosaveFileName();
3926 if (newauto != oldauto && oldauto.exists())
3927 if (!oldauto.moveTo(newauto))
3928 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3932 bool Buffer::autoSave() const
3934 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3935 if (buf->d->bak_clean || isReadonly())
3938 message(_("Autosaving current document..."));
3939 buf->d->bak_clean = true;
3941 FileName const fname = getAutosaveFileName();
3942 LASSERT(d->cloned_buffer_, return false);
3944 // If this buffer is cloned, we assume that
3945 // we are running in a separate thread already.
3946 TempFile tempfile("lyxautoXXXXXX.lyx");
3947 tempfile.setAutoRemove(false);
3948 FileName const tmp_ret = tempfile.name();
3949 if (!tmp_ret.empty()) {
3951 // assume successful write of tmp_ret
3952 if (tmp_ret.moveTo(fname))
3955 // failed to write/rename tmp_ret so try writing direct
3956 return writeFile(fname);
3960 void Buffer::setExportStatus(bool e) const
3962 d->doing_export = e;
3963 ListOfBuffers clist = getDescendents();
3964 ListOfBuffers::const_iterator cit = clist.begin();
3965 ListOfBuffers::const_iterator const cen = clist.end();
3966 for (; cit != cen; ++cit)
3967 (*cit)->d->doing_export = e;
3971 bool Buffer::isExporting() const
3973 return d->doing_export;
3977 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3981 return doExport(target, put_in_tempdir, result_file);
3984 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3985 string & result_file) const
3987 bool const update_unincluded =
3988 params().maintain_unincluded_children
3989 && !params().getIncludedChildren().empty();
3991 // (1) export with all included children (omit \includeonly)
3992 if (update_unincluded) {
3993 ExportStatus const status =
3994 doExport(target, put_in_tempdir, true, result_file);
3995 if (status != ExportSuccess)
3998 // (2) export with included children only
3999 return doExport(target, put_in_tempdir, false, result_file);
4003 void Buffer::setMathFlavor(OutputParams & op) const
4005 switch (params().html_math_output) {
4006 case BufferParams::MathML:
4007 op.math_flavor = OutputParams::MathAsMathML;
4009 case BufferParams::HTML:
4010 op.math_flavor = OutputParams::MathAsHTML;
4012 case BufferParams::Images:
4013 op.math_flavor = OutputParams::MathAsImages;
4015 case BufferParams::LaTeX:
4016 op.math_flavor = OutputParams::MathAsLaTeX;
4022 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4023 bool includeall, string & result_file) const
4025 LYXERR(Debug::FILES, "target=" << target);
4026 OutputParams runparams(¶ms().encoding());
4027 string format = target;
4028 string dest_filename;
4029 size_t pos = target.find(' ');
4030 if (pos != string::npos) {
4031 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4032 format = target.substr(0, pos);
4033 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4034 FileName(dest_filename).onlyPath().createPath();
4035 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4037 MarkAsExporting exporting(this);
4038 string backend_format;
4039 runparams.flavor = OutputParams::LATEX;
4040 runparams.linelen = lyxrc.plaintext_linelen;
4041 runparams.includeall = includeall;
4042 vector<string> backs = params().backends();
4043 Converters converters = theConverters();
4044 bool need_nice_file = false;
4045 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4046 // Get shortest path to format
4047 converters.buildGraph();
4048 Graph::EdgePath path;
4049 for (vector<string>::const_iterator it = backs.begin();
4050 it != backs.end(); ++it) {
4051 Graph::EdgePath p = converters.getPath(*it, format);
4052 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4053 backend_format = *it;
4058 if (!put_in_tempdir) {
4059 // Only show this alert if this is an export to a non-temporary
4060 // file (not for previewing).
4061 Alert::error(_("Couldn't export file"), bformat(
4062 _("No information for exporting the format %1$s."),
4063 formats.prettyName(format)));
4065 return ExportNoPathToFormat;
4067 runparams.flavor = converters.getFlavor(path, this);
4068 Graph::EdgePath::const_iterator it = path.begin();
4069 Graph::EdgePath::const_iterator en = path.end();
4070 for (; it != en; ++it)
4071 if (theConverters().get(*it).nice()) {
4072 need_nice_file = true;
4077 backend_format = format;
4078 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4079 // FIXME: Don't hardcode format names here, but use a flag
4080 if (backend_format == "pdflatex")
4081 runparams.flavor = OutputParams::PDFLATEX;
4082 else if (backend_format == "luatex")
4083 runparams.flavor = OutputParams::LUATEX;
4084 else if (backend_format == "dviluatex")
4085 runparams.flavor = OutputParams::DVILUATEX;
4086 else if (backend_format == "xetex")
4087 runparams.flavor = OutputParams::XETEX;
4090 string filename = latexName(false);
4091 filename = addName(temppath(), filename);
4092 filename = changeExtension(filename,
4093 formats.extension(backend_format));
4094 LYXERR(Debug::FILES, "filename=" << filename);
4096 // Plain text backend
4097 if (backend_format == "text") {
4098 runparams.flavor = OutputParams::TEXT;
4099 writePlaintextFile(*this, FileName(filename), runparams);
4102 else if (backend_format == "xhtml") {
4103 runparams.flavor = OutputParams::HTML;
4104 setMathFlavor(runparams);
4105 makeLyXHTMLFile(FileName(filename), runparams);
4106 } else if (backend_format == "lyx")
4107 writeFile(FileName(filename));
4109 else if (params().isDocBook()) {
4110 runparams.nice = !put_in_tempdir;
4111 makeDocBookFile(FileName(filename), runparams);
4114 else if (backend_format == format || need_nice_file) {
4115 runparams.nice = true;
4116 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4117 if (d->cloned_buffer_)
4118 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4121 } else if (!lyxrc.tex_allows_spaces
4122 && contains(filePath(), ' ')) {
4123 Alert::error(_("File name error"),
4124 _("The directory path to the document cannot contain spaces."));
4125 return ExportTexPathHasSpaces;
4127 runparams.nice = false;
4128 bool const success = makeLaTeXFile(
4129 FileName(filename), filePath(), runparams);
4130 if (d->cloned_buffer_)
4131 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4136 string const error_type = (format == "program")
4137 ? "Build" : params().bufferFormat();
4138 ErrorList & error_list = d->errorLists[error_type];
4139 string const ext = formats.extension(format);
4140 FileName const tmp_result_file(changeExtension(filename, ext));
4141 bool const success = converters.convert(this, FileName(filename),
4142 tmp_result_file, FileName(absFileName()), backend_format, format,
4145 // Emit the signal to show the error list or copy it back to the
4146 // cloned Buffer so that it can be emitted afterwards.
4147 if (format != backend_format) {
4148 if (runparams.silent)
4150 else if (d->cloned_buffer_)
4151 d->cloned_buffer_->d->errorLists[error_type] =
4152 d->errorLists[error_type];
4155 // also to the children, in case of master-buffer-view
4156 ListOfBuffers clist = getDescendents();
4157 ListOfBuffers::const_iterator cit = clist.begin();
4158 ListOfBuffers::const_iterator const cen = clist.end();
4159 for (; cit != cen; ++cit) {
4160 if (runparams.silent)
4161 (*cit)->d->errorLists[error_type].clear();
4162 else if (d->cloned_buffer_) {
4163 // Enable reverse search by copying back the
4164 // texrow object to the cloned buffer.
4165 // FIXME: this is not thread safe.
4166 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4167 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4168 (*cit)->d->errorLists[error_type];
4170 (*cit)->errors(error_type, true);
4174 if (d->cloned_buffer_) {
4175 // Enable reverse dvi or pdf to work by copying back the texrow
4176 // object to the cloned buffer.
4177 // FIXME: There is a possibility of concurrent access to texrow
4178 // here from the main GUI thread that should be securized.
4179 d->cloned_buffer_->d->texrow = d->texrow;
4180 string const error_type = params().bufferFormat();
4181 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4185 if (put_in_tempdir) {
4186 result_file = tmp_result_file.absFileName();
4187 return success ? ExportSuccess : ExportConverterError;
4190 if (dest_filename.empty())
4191 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4193 result_file = dest_filename;
4194 // We need to copy referenced files (e. g. included graphics
4195 // if format == "dvi") to the result dir.
4196 vector<ExportedFile> const files =
4197 runparams.exportdata->externalFiles(format);
4198 string const dest = runparams.export_folder.empty() ?
4199 onlyPath(result_file) : runparams.export_folder;
4200 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4201 : force_overwrite == ALL_FILES;
4202 CopyStatus status = use_force ? FORCE : SUCCESS;
4204 vector<ExportedFile>::const_iterator it = files.begin();
4205 vector<ExportedFile>::const_iterator const en = files.end();
4206 for (; it != en && status != CANCEL; ++it) {
4207 string const fmt = formats.getFormatFromFile(it->sourceName);
4208 string fixedName = it->exportName;
4209 if (!runparams.export_folder.empty()) {
4210 // Relative pathnames starting with ../ will be sanitized
4211 // if exporting to a different folder
4212 while (fixedName.substr(0, 3) == "../")
4213 fixedName = fixedName.substr(3, fixedName.length() - 3);
4215 FileName fixedFileName = makeAbsPath(fixedName, dest);
4216 fixedFileName.onlyPath().createPath();
4217 status = copyFile(fmt, it->sourceName,
4219 it->exportName, status == FORCE,
4220 runparams.export_folder.empty());
4223 if (status == CANCEL) {
4224 message(_("Document export cancelled."));
4225 return ExportCancel;
4228 if (tmp_result_file.exists()) {
4229 // Finally copy the main file
4230 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4231 : force_overwrite != NO_FILES;
4232 if (status == SUCCESS && use_force)
4234 status = copyFile(format, tmp_result_file,
4235 FileName(result_file), result_file,
4237 if (status == CANCEL) {
4238 message(_("Document export cancelled."));
4239 return ExportCancel;
4241 message(bformat(_("Document exported as %1$s "
4243 formats.prettyName(format),
4244 makeDisplayPath(result_file)));
4247 // This must be a dummy converter like fax (bug 1888)
4248 message(bformat(_("Document exported as %1$s"),
4249 formats.prettyName(format)));
4252 return success ? ExportSuccess : ExportConverterError;
4256 Buffer::ExportStatus Buffer::preview(string const & format) const
4258 bool const update_unincluded =
4259 params().maintain_unincluded_children
4260 && !params().getIncludedChildren().empty();
4261 return preview(format, update_unincluded);
4265 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4267 MarkAsExporting exporting(this);
4269 // (1) export with all included children (omit \includeonly)
4271 ExportStatus const status = doExport(format, true, true, result_file);
4272 if (status != ExportSuccess)
4275 // (2) export with included children only
4276 ExportStatus const status = doExport(format, true, false, result_file);
4277 FileName const previewFile(result_file);
4279 LATTEST (isClone());
4280 d->cloned_buffer_->d->preview_file_ = previewFile;
4281 d->cloned_buffer_->d->preview_format_ = format;
4282 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4284 if (status != ExportSuccess)
4286 if (previewFile.exists()) {
4287 if (!formats.view(*this, previewFile, format))
4288 return PreviewError;
4290 return PreviewSuccess;
4293 // Successful export but no output file?
4294 // Probably a bug in error detection.
4295 LATTEST (status != ExportSuccess);
4302 Buffer::ReadStatus Buffer::extractFromVC()
4304 bool const found = LyXVC::file_not_found_hook(d->filename);
4306 return ReadFileNotFound;
4307 if (!d->filename.isReadableFile())
4313 Buffer::ReadStatus Buffer::loadEmergency()
4315 FileName const emergencyFile = getEmergencyFileName();
4316 if (!emergencyFile.exists()
4317 || emergencyFile.lastModified() <= d->filename.lastModified())
4318 return ReadFileNotFound;
4320 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4321 docstring const text = bformat(_("An emergency save of the document "
4322 "%1$s exists.\n\nRecover emergency save?"), file);
4324 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4325 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4331 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4332 bool const success = (ret_llf == ReadSuccess);
4335 Alert::warning(_("File is read-only"),
4336 bformat(_("An emergency file is successfully loaded, "
4337 "but the original file %1$s is marked read-only. "
4338 "Please make sure to save the document as a different "
4339 "file."), from_utf8(d->filename.absFileName())));
4342 lyxvc().file_found_hook(d->filename);
4343 str = _("Document was successfully recovered.");
4345 str = _("Document was NOT successfully recovered.");
4346 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4347 makeDisplayPath(emergencyFile.absFileName()));
4349 int const del_emerg =
4350 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4351 _("&Remove"), _("&Keep"));
4352 if (del_emerg == 0) {
4353 emergencyFile.removeFile();
4355 Alert::warning(_("Emergency file deleted"),
4356 _("Do not forget to save your file now!"), true);
4358 return success ? ReadSuccess : ReadEmergencyFailure;
4361 int const del_emerg =
4362 Alert::prompt(_("Delete emergency file?"),
4363 _("Remove emergency file now?"), 1, 1,
4364 _("&Remove"), _("&Keep"));
4366 emergencyFile.removeFile();
4367 return ReadOriginal;
4377 Buffer::ReadStatus Buffer::loadAutosave()
4379 // Now check if autosave file is newer.
4380 FileName const autosaveFile = getAutosaveFileName();
4381 if (!autosaveFile.exists()
4382 || autosaveFile.lastModified() <= d->filename.lastModified())
4383 return ReadFileNotFound;
4385 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4386 docstring const text = bformat(_("The backup of the document %1$s "
4387 "is newer.\n\nLoad the backup instead?"), file);
4388 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4389 _("&Load backup"), _("Load &original"), _("&Cancel"));
4394 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4395 // the file is not saved if we load the autosave file.
4396 if (ret_llf == ReadSuccess) {
4398 Alert::warning(_("File is read-only"),
4399 bformat(_("A backup file is successfully loaded, "
4400 "but the original file %1$s is marked read-only. "
4401 "Please make sure to save the document as a "
4403 from_utf8(d->filename.absFileName())));
4406 lyxvc().file_found_hook(d->filename);
4409 return ReadAutosaveFailure;
4412 // Here we delete the autosave
4413 autosaveFile.removeFile();
4414 return ReadOriginal;
4422 Buffer::ReadStatus Buffer::loadLyXFile()
4424 if (!d->filename.isReadableFile()) {
4425 ReadStatus const ret_rvc = extractFromVC();
4426 if (ret_rvc != ReadSuccess)
4430 ReadStatus const ret_re = loadEmergency();
4431 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4434 ReadStatus const ret_ra = loadAutosave();
4435 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4438 return loadThisLyXFile(d->filename);
4442 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4444 return readFile(fn);
4448 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4450 TeXErrors::Errors::const_iterator it = terr.begin();
4451 TeXErrors::Errors::const_iterator end = terr.end();
4452 ListOfBuffers clist = getDescendents();
4453 ListOfBuffers::const_iterator cen = clist.end();
4455 for (; it != end; ++it) {
4458 int errorRow = it->error_in_line;
4459 Buffer const * buf = 0;
4461 if (it->child_name.empty())
4462 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4464 // The error occurred in a child
4465 ListOfBuffers::const_iterator cit = clist.begin();
4466 for (; cit != cen; ++cit) {
4467 string const child_name =
4468 DocFileName(changeExtension(
4469 (*cit)->absFileName(), "tex")).
4471 if (it->child_name != child_name)
4473 (*cit)->d->texrow.getIdFromRow(errorRow,
4474 id_start, pos_start);
4475 if (id_start != -1) {
4476 buf = d->cloned_buffer_
4477 ? (*cit)->d->cloned_buffer_->d->owner_
4478 : (*cit)->d->owner_;
4489 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4490 } while (found && id_start == id_end && pos_start == pos_end);
4492 if (id_start != id_end) {
4493 // Next registered position is outside the inset where
4494 // the error occurred, so signal end-of-paragraph
4498 errorList.push_back(ErrorItem(it->error_desc,
4499 it->error_text, id_start, pos_start, pos_end, buf));
4504 void Buffer::setBuffersForInsets() const
4506 inset().setBuffer(const_cast<Buffer &>(*this));
4510 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4512 LBUFERR(!text().paragraphs().empty());
4514 // Use the master text class also for child documents
4515 Buffer const * const master = masterBuffer();
4516 DocumentClass const & textclass = master->params().documentClass();
4518 // do this only if we are the top-level Buffer
4519 if (master == this) {
4520 textclass.counters().reset(from_ascii("bibitem"));
4521 reloadBibInfoCache();
4524 // keep the buffers to be children in this set. If the call from the
4525 // master comes back we can see which of them were actually seen (i.e.
4526 // via an InsetInclude). The remaining ones in the set need still be updated.
4527 static std::set<Buffer const *> bufToUpdate;
4528 if (scope == UpdateMaster) {
4529 // If this is a child document start with the master
4530 if (master != this) {
4531 bufToUpdate.insert(this);
4532 master->updateBuffer(UpdateMaster, utype);
4533 // If the master buffer has no gui associated with it, then the TocModel is
4534 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4535 // (bug 5699). The same happens if the master buffer is open in a different
4536 // window. This test catches both possibilities.
4537 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4538 // There remains a problem here: If there is another child open in yet a third
4539 // window, that TOC is not updated. So some more general solution is needed at
4541 if (master->d->gui_ != d->gui_)
4544 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4545 if (bufToUpdate.find(this) == bufToUpdate.end())
4549 // start over the counters in the master
4550 textclass.counters().reset();
4553 // update will be done below for this buffer
4554 bufToUpdate.erase(this);
4556 // update all caches
4557 clearReferenceCache();
4560 Buffer & cbuf = const_cast<Buffer &>(*this);
4563 ParIterator parit = cbuf.par_iterator_begin();
4564 updateBuffer(parit, utype);
4567 // TocBackend update will be done later.
4570 d->bibinfo_cache_valid_ = true;
4571 d->cite_labels_valid_ = true;
4572 cbuf.tocBackend().update(utype == OutputUpdate);
4573 if (scope == UpdateMaster)
4574 cbuf.structureChanged();
4578 static depth_type getDepth(DocIterator const & it)
4580 depth_type depth = 0;
4581 for (size_t i = 0 ; i < it.depth() ; ++i)
4582 if (!it[i].inset().inMathed())
4583 depth += it[i].paragraph().getDepth() + 1;
4584 // remove 1 since the outer inset does not count
4588 static depth_type getItemDepth(ParIterator const & it)
4590 Paragraph const & par = *it;
4591 LabelType const labeltype = par.layout().labeltype;
4593 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4596 // this will hold the lowest depth encountered up to now.
4597 depth_type min_depth = getDepth(it);
4598 ParIterator prev_it = it;
4601 --prev_it.top().pit();
4603 // start of nested inset: go to outer par
4605 if (prev_it.empty()) {
4606 // start of document: nothing to do
4611 // We search for the first paragraph with same label
4612 // that is not more deeply nested.
4613 Paragraph & prev_par = *prev_it;
4614 depth_type const prev_depth = getDepth(prev_it);
4615 if (labeltype == prev_par.layout().labeltype) {
4616 if (prev_depth < min_depth)
4617 return prev_par.itemdepth + 1;
4618 if (prev_depth == min_depth)
4619 return prev_par.itemdepth;
4621 min_depth = min(min_depth, prev_depth);
4622 // small optimization: if we are at depth 0, we won't
4623 // find anything else
4624 if (prev_depth == 0)
4630 static bool needEnumCounterReset(ParIterator const & it)
4632 Paragraph const & par = *it;
4633 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4634 depth_type const cur_depth = par.getDepth();
4635 ParIterator prev_it = it;
4636 while (prev_it.pit()) {
4637 --prev_it.top().pit();
4638 Paragraph const & prev_par = *prev_it;
4639 if (prev_par.getDepth() <= cur_depth)
4640 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4642 // start of nested inset: reset
4647 // set the label of a paragraph. This includes the counters.
4648 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4650 BufferParams const & bp = owner_->masterBuffer()->params();
4651 DocumentClass const & textclass = bp.documentClass();
4652 Paragraph & par = it.paragraph();
4653 Layout const & layout = par.layout();
4654 Counters & counters = textclass.counters();
4656 if (par.params().startOfAppendix()) {
4657 // We want to reset the counter corresponding to toplevel sectioning
4658 Layout const & lay = textclass.getTOCLayout();
4659 docstring const cnt = lay.counter;
4661 counters.reset(cnt);
4662 counters.appendix(true);
4664 par.params().appendix(counters.appendix());
4666 // Compute the item depth of the paragraph
4667 par.itemdepth = getItemDepth(it);
4669 if (layout.margintype == MARGIN_MANUAL) {
4670 if (par.params().labelWidthString().empty())
4671 par.params().labelWidthString(par.expandLabel(layout, bp));
4672 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4673 // we do not need to do anything here, since the empty case is
4674 // handled during export.
4676 par.params().labelWidthString(docstring());
4679 switch(layout.labeltype) {
4680 case LABEL_ITEMIZE: {
4681 // At some point of time we should do something more
4682 // clever here, like:
4683 // par.params().labelString(
4684 // bp.user_defined_bullet(par.itemdepth).getText());
4685 // for now, use a simple hardcoded label
4686 docstring itemlabel;
4687 switch (par.itemdepth) {
4689 itemlabel = char_type(0x2022);
4692 itemlabel = char_type(0x2013);
4695 itemlabel = char_type(0x2217);
4698 itemlabel = char_type(0x2219); // or 0x00b7
4701 par.params().labelString(itemlabel);
4705 case LABEL_ENUMERATE: {
4706 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4708 switch (par.itemdepth) {
4717 enumcounter += "iv";
4720 // not a valid enumdepth...
4724 // Maybe we have to reset the enumeration counter.
4725 if (needEnumCounterReset(it))
4726 counters.reset(enumcounter);
4727 counters.step(enumcounter, utype);
4729 string const & lang = par.getParLanguage(bp)->code();
4730 par.params().labelString(counters.theCounter(enumcounter, lang));
4735 case LABEL_SENSITIVE: {
4736 string const & type = counters.current_float();
4737 docstring full_label;
4739 full_label = owner_->B_("Senseless!!! ");
4741 docstring name = owner_->B_(textclass.floats().getType(type).name());
4742 if (counters.hasCounter(from_utf8(type))) {
4743 string const & lang = par.getParLanguage(bp)->code();
4744 counters.step(from_utf8(type), utype);
4745 full_label = bformat(from_ascii("%1$s %2$s:"),
4747 counters.theCounter(from_utf8(type), lang));
4749 full_label = bformat(from_ascii("%1$s #:"), name);
4751 par.params().labelString(full_label);
4755 case LABEL_NO_LABEL:
4756 par.params().labelString(docstring());
4760 case LABEL_CENTERED:
4761 case LABEL_STATIC: {
4762 docstring const & lcounter = layout.counter;
4763 if (!lcounter.empty()) {
4764 if (layout.toclevel <= bp.secnumdepth
4765 && (layout.latextype != LATEX_ENVIRONMENT
4766 || it.text()->isFirstInSequence(it.pit()))) {
4767 if (counters.hasCounter(lcounter))
4768 counters.step(lcounter, utype);
4769 par.params().labelString(par.expandLabel(layout, bp));
4771 par.params().labelString(docstring());
4773 par.params().labelString(par.expandLabel(layout, bp));
4779 par.params().labelString(par.expandLabel(layout, bp));
4784 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4786 // LASSERT: Is it safe to continue here, or should we just return?
4787 LASSERT(parit.pit() == 0, /**/);
4789 // Set the position of the text in the buffer to be able
4790 // to resolve macros in it.
4791 parit.text()->setMacrocontextPosition(parit);
4793 depth_type maxdepth = 0;
4794 pit_type const lastpit = parit.lastpit();
4795 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4796 // reduce depth if necessary
4797 if (parit->params().depth() > maxdepth) {
4798 /** FIXME: this function is const, but
4799 * nevertheless it modifies the buffer. To be
4800 * cleaner, one should modify the buffer in
4801 * another function, which is actually
4802 * non-const. This would however be costly in
4803 * terms of code duplication.
4805 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4806 parit->params().depth(maxdepth);
4808 maxdepth = parit->getMaxDepthAfter();
4810 if (utype == OutputUpdate) {
4811 // track the active counters
4812 // we have to do this for the master buffer, since the local
4813 // buffer isn't tracking anything.
4814 masterBuffer()->params().documentClass().counters().
4815 setActiveLayout(parit->layout());
4818 // set the counter for this paragraph
4819 d->setLabel(parit, utype);
4822 InsetList::const_iterator iit = parit->insetList().begin();
4823 InsetList::const_iterator end = parit->insetList().end();
4824 for (; iit != end; ++iit) {
4825 parit.pos() = iit->pos;
4826 iit->inset->updateBuffer(parit, utype);
4832 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4833 WordLangTuple & word_lang, docstring_list & suggestions) const
4837 suggestions.clear();
4838 word_lang = WordLangTuple();
4839 bool const to_end = to.empty();
4840 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4841 // OK, we start from here.
4842 for (; from != end; from.forwardPos()) {
4843 // This skips all insets with spell check disabled.
4844 while (!from.allowSpellCheck()) {
4848 // If from is at the end of the document (which is possible
4849 // when "from" was changed above) LyX will crash later otherwise.
4850 if (from.atEnd() || (!to_end && from >= end))
4853 from.paragraph().spellCheck();
4854 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4855 if (SpellChecker::misspelled(res)) {
4859 // Do not increase progress when from == to, otherwise the word
4860 // count will be wrong.
4870 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4872 bool inword = false;
4877 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4878 if (!dit.inTexted()) {
4883 Paragraph const & par = dit.paragraph();
4884 pos_type const pos = dit.pos();
4886 // Copied and adapted from isWordSeparator() in Paragraph
4887 if (pos == dit.lastpos()) {
4890 Inset const * ins = par.getInset(pos);
4891 if (ins && skipNoOutput && !ins->producesOutput()) {
4894 // stop if end of range was skipped
4895 if (!to.atEnd() && dit >= to)
4898 } else if (!par.isDeleted(pos)) {
4899 if (par.isWordSeparator(pos))
4905 if (ins && ins->isLetter())
4907 else if (ins && ins->isSpace())
4910 char_type const c = par.getChar(pos);
4911 if (isPrintableNonspace(c))
4913 else if (isSpace(c))
4923 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4925 d->updateStatistics(from, to, skipNoOutput);
4929 int Buffer::wordCount() const
4931 return d->wordCount();
4935 int Buffer::charCount(bool with_blanks) const
4937 return d->charCount(with_blanks);
4941 Buffer::ReadStatus Buffer::reload()
4944 // c.f. bug http://www.lyx.org/trac/ticket/6587
4945 removeAutosaveFile();
4946 // e.g., read-only status could have changed due to version control
4947 d->filename.refresh();
4948 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4950 // clear parent. this will get reset if need be.
4952 ReadStatus const status = loadLyXFile();
4953 if (status == ReadSuccess) {
4958 message(bformat(_("Document %1$s reloaded."), disp_fn));
4961 message(bformat(_("Could not reload document %1$s."), disp_fn));
4971 bool Buffer::saveAs(FileName const & fn)
4973 FileName const old_name = fileName();
4974 FileName const old_auto = getAutosaveFileName();
4975 bool const old_unnamed = isUnnamed();
4976 bool success = true;
4977 d->old_position = filePath();
4984 // bring the autosave file with us, just in case.
4985 moveAutosaveFile(old_auto);
4986 // validate version control data and
4987 // correct buffer title
4988 lyxvc().file_found_hook(fileName());
4990 // the file has now been saved to the new location.
4991 // we need to check that the locations of child buffers
4993 checkChildBuffers();
4994 checkMasterBuffer();
4997 // reset the old filename and unnamed state
4998 setFileName(old_name);
4999 setUnnamed(old_unnamed);
5003 d->old_position.clear();
5008 void Buffer::checkChildBuffers()
5010 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5011 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5012 for (; it != en; ++it) {
5013 DocIterator dit = it->second;
5014 Buffer * cbuf = const_cast<Buffer *>(it->first);
5015 if (!cbuf || !theBufferList().isLoaded(cbuf))
5017 Inset * inset = dit.nextInset();
5018 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5019 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5020 docstring const & incfile = inset_inc->getParam("filename");
5021 string oldloc = cbuf->absFileName();
5022 string newloc = makeAbsPath(to_utf8(incfile),
5023 onlyPath(absFileName())).absFileName();
5024 if (oldloc == newloc)
5026 // the location of the child file is incorrect.
5028 inset_inc->setChildBuffer(0);
5030 // invalidate cache of children
5031 d->children_positions.clear();
5032 d->position_to_children.clear();
5036 // If a child has been saved under a different name/path, it might have been
5037 // orphaned. Therefore the master needs to be reset (bug 8161).
5038 void Buffer::checkMasterBuffer()
5040 Buffer const * const master = masterBuffer();
5044 // necessary to re-register the child (bug 5873)
5045 // FIXME: clean up updateMacros (here, only
5046 // child registering is needed).
5047 master->updateMacros();
5048 // (re)set master as master buffer, but only
5049 // if we are a real child
5050 if (master->isChild(this))
5057 string Buffer::includedFilePath(string const & name, string const & ext) const
5059 bool isabsolute = FileName::isAbsolute(name);
5060 // old_position already contains a trailing path separator
5061 string const absname = isabsolute ? name : d->old_position + name;
5063 if (d->old_position.empty() || d->old_position == filePath()
5064 || !FileName(addExtension(absname, ext)).exists())
5068 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5070 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5071 from_utf8(filePath())));