]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Attempt to fix bug #13017.
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "FuncCode.h"
16 #include "OutputEnums.h"
17
18 #include "support/unique_ptr.h"
19 #include "support/strfwd.h"
20 #include "support/types.h"
21
22 #include <map>
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BibTeXInfo;
33 class BufferParams;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorList;
38 class FuncRequest;
39 class FuncStatus;
40 class Inset;
41 class InsetLabel;
42 class Lexer;
43 class Text;
44 class LyXVC;
45 class LaTeXFeatures;
46 class Language;
47 class MacroData;
48 class MacroNameSet;
49 class MacroSet;
50 class OutputParams;
51 class otexstream;
52 class ParagraphList;
53 class ParIterator;
54 class ParConstIterator;
55 class TeXErrors;
56 class TexRow;
57 class TocBackend;
58 class Undo;
59 class WordLangTuple;
60
61 namespace frontend {
62 class GuiBufferDelegate;
63 class WorkAreaManager;
64 } // namespace frontend
65
66 namespace support {
67 class DocFileName;
68 class FileName;
69 class FileNameList;
70 } // namespace support
71
72 namespace graphics {
73 class PreviewLoader;
74 class Cache;
75 } // namespace graphics
76
77
78 class Buffer;
79 typedef std::list<Buffer *> ListOfBuffers;
80 /// a list of Buffers we cloned
81 typedef std::set<Buffer *> CloneList;
82 typedef std::shared_ptr<CloneList> CloneList_ptr;
83
84
85 /** The buffer object.
86  * This is the buffer object. It contains all the information about
87  * a document loaded into LyX.
88  * The buffer object owns the Text (wrapped in an InsetText), which
89  * contains the individual paragraphs of the document.
90  *
91  *
92  * I am not sure if the class is complete or
93  * minimal, probably not.
94  * \author Lars Gullik Bjønnes
95  */
96
97 class Buffer {
98 public:
99         /// What type of log will \c getLogName() return?
100         enum LogType {
101                 latexlog, ///< LaTeX log
102                 buildlog  ///< Literate build log
103         };
104
105         /// Result of \c readFile()
106         enum ReadStatus {
107                 ReadSuccess,
108                 ReadCancel,
109                 // failures
110                 ReadFailure,
111                 ReadWrongVersion,
112                 ReadFileNotFound,
113                 ReadVCError,
114                 ReadAutosaveFailure,
115                 ReadEmergencyFailure,
116                 ReadNoLyXFormat,
117                 ReadDocumentFailure,
118                 // lyx2lyx
119                 LyX2LyXNoTempFile,
120                 LyX2LyXNotFound,
121                 LyX2LyXOlderFormat,
122                 LyX2LyXNewerFormat,
123                 // other
124                 ReadOriginal
125         };
126
127         enum ExportStatus {
128                 // export
129                 ExportSuccess,
130                 ExportCancel,
131                 ExportKilled,
132                 ExportError,
133                 ExportNoPathToFormat,
134                 ExportTexPathHasSpaces,
135                 ExportConverterError,
136                 // preview
137                 // Implies ExportSuccess.
138                 PreviewSuccess,
139                 // The exported file exists but there was an error when opening
140                 // it in a viewer.
141                 PreviewError
142         };
143
144         ///
145         enum UpdateScope {
146                 UpdateMaster,
147                 UpdateChildOnly
148         };
149
150         /// Constructor
151         explicit Buffer(std::string const & file, bool readonly = false,
152                 Buffer const * cloned_buffer = nullptr);
153
154         /// Destructor
155         ~Buffer();
156
157         /// Clones the entire structure of which this Buffer is part,
158         /// cloning all the children, too.
159         Buffer * cloneWithChildren() const;
160         /// Just clones this single Buffer. For autosave.
161         Buffer * cloneBufferOnly() const;
162         ///
163         bool isClone() const;
164
165         /// Helper method: dispatch this branch activation LFUN
166         /// Retunrs true if the function has been dispatched
167         bool branchActivationDispatch(FuncCode act, docstring const & branch);
168
169         /** High-level interface to buffer functionality.
170             This function parses a command string and executes it.
171         */
172         void dispatch(std::string const & command, DispatchResult & result);
173
174         /// Maybe we know the function already by number...
175         void dispatch(FuncRequest const & func, DispatchResult & result);
176
177         /// Helper method: Is this buffer activation LFUN enabled?
178         bool branchActivationEnabled(FuncCode act, docstring const & branch) const;
179
180         /// Can this function be exectued?
181         /// \return true if we made a decision
182         bool getStatus(FuncRequest const & cmd, FuncStatus & flag) const;
183
184         ///
185         DocIterator getParFromID(int id) const;
186         /// do we have a paragraph with this id?
187         bool hasParWithID(int id) const;
188
189         ///
190         frontend::WorkAreaManager & workAreaManager() const;
191
192         /** Save file.
193             Takes care of auto-save files and backup file if requested.
194             Returns \c true if the save is successful, \c false otherwise.
195         */
196         bool save() const;
197         /// Renames and saves the buffer
198         bool saveAs(support::FileName const & fn);
199
200         /// Write document to stream. Returns \c false if unsuccessful.
201         bool write(std::ostream &) const;
202         /// Write file. Returns \c false if unsuccessful.
203         bool writeFile(support::FileName const &) const;
204
205         /// \name Functions involved in reading files/strings.
206         //@{
207         /// Loads the LyX file into the buffer. This function
208         /// tries to extract the file from version control if it
209         /// cannot be found. If it can be found, it will try to
210         /// read an emergency save file or an autosave file.
211         /// \sa loadThisLyXFile
212         ReadStatus loadLyXFile();
213         /// Loads the LyX file \c fn into the buffer. If you want
214         /// to check for files in a version control container,
215         /// emergency or autosave files, one should use \c loadLyXFile.
216         /// /sa loadLyXFile
217         ReadStatus loadThisLyXFile(support::FileName const & fn);
218         /// import a new document from a string
219         bool importString(std::string const &, docstring const &, ErrorList &);
220         /// import a new file
221         bool importFile(std::string const &, support::FileName const &, ErrorList &);
222         /// read a new document from a string
223         bool readString(std::string const &);
224         /// Reloads the LyX file
225         ReadStatus reload();
226 //FIXME: The following function should be private
227 //private:
228         /// read the header, returns number of unknown tokens
229         int readHeader(Lexer & lex);
230
231         double fontScalingFactor() const;
232         /// check for active synctex support:
233         /// - either the document has synchronize output enabled or
234         /// - there is a converter to dvi or pdf defined with synctex command line argument
235         ///   this is the "expert mode", false positives are possible
236         bool isSyncTeXenabled() const;
237
238 private:
239         ///
240         typedef std::map<Buffer const *, Buffer *> BufferMap;
241         ///
242         void cloneWithChildren(BufferMap &, CloneList_ptr) const;
243         /// save checksum of the given file.
244         void saveCheckSum() const;
245         /// read a new file
246         ReadStatus readFile(support::FileName const & fn);
247         /// Reads a file without header.
248         /// \param par if != 0 insert the file.
249         /// \return \c true if file is not completely read.
250         bool readDocument(Lexer &);
251         /// Try to extract the file from a version control container
252         /// before reading if the file cannot be found.
253         /// \sa LyXVC::file_not_found_hook
254         ReadStatus extractFromVC();
255         /// Reads the first tag of a LyX File and
256         /// returns the file format number.
257         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
258                 int & file_format) const;
259         /// Convert the LyX file to the LYX_FORMAT using
260         /// the lyx2lyx script and returns the filename
261         /// of the temporary file to be read
262         ReadStatus convertLyXFormat(support::FileName const & fn,
263                 support::FileName & tmpfile, int from_format);
264         /// get appropriate name for backing up files from older versions
265         support::FileName getBackupName() const;
266         //@}
267
268 public:
269         /// \name Functions involved in autosave and emergency files.
270         //@{
271         /// Save an autosave file to #filename.lyx#
272         bool autoSave() const;
273         /// save emergency file
274         /// \return a status message towards the user.
275         docstring emergencyWrite() const;
276
277 //FIXME:The following function should be private
278 //private:
279         ///
280         void removeAutosaveFile() const;
281
282 private:
283         /// Try to load an autosave file associated to \c fn.
284         ReadStatus loadAutosave();
285         /// Try to load an emergency file associated to \c fn.
286         ReadStatus loadEmergency();
287         /// Get the filename of the emergency file associated with the Buffer
288         support::FileName getEmergencyFileName() const;
289         /// Get the filename of the autosave file associated with the Buffer
290         support::FileName getAutosaveFileName() const;
291         ///
292         void moveAutosaveFile(support::FileName const & old) const;
293         //@}
294
295 public:
296         /// Fill in the ErrorList with the TeXErrors
297         void bufferErrors(TeXErrors const &, ErrorList &) const;
298         /// Fill in the Citation/Reference ErrorList from the TeXErrors
299         void bufferRefs(TeXErrors const &, ErrorList &) const;
300
301         enum OutputWhat {
302                 FullSource,
303                 OnlyBody,
304                 IncludedFile,
305                 OnlyPreamble,
306                 CurrentParagraph
307         };
308
309         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
310         ExportStatus makeLaTeXFile(support::FileName const & filename,
311                            std::string const & original_path,
312                            OutputParams const &,
313                            OutputWhat output = FullSource) const;
314         /** Export the buffer to LaTeX.
315             If \p os is a file stream, and params().inputenc is "auto-legacy" or
316             "auto-legacy-plain", and the buffer contains text in different languages
317             with more than one encoding, then this method will change the
318             encoding associated to \p os. Therefore you must not call this
319             method with a string stream if the output is supposed to go to a
320             file. \code
321             ofdocstream ofs;
322             otexstream os(ofs);
323             ofs.open("test.tex");
324             writeLaTeXSource(os, ...);
325             ofs.close();
326             \endcode is NOT equivalent to \code
327             odocstringstream oss;
328             otexstream os(oss);
329             writeLaTeXSource(os, ...);
330             ofdocstream ofs;
331             ofs.open("test.tex");
332             ofs << oss.str();
333             ofs.close();
334             \endcode
335          */
336         ExportStatus writeLaTeXSource(otexstream & os,
337                            std::string const & original_path,
338                            OutputParams const &,
339                            OutputWhat output = FullSource) const;
340         ///
341         ExportStatus makeDocBookFile(support::FileName const & filename,
342                              OutputParams const & runparams_in,
343                              OutputWhat output = FullSource) const;
344         ///
345         ExportStatus writeDocBookSource(odocstream & os,
346                                  OutputParams const & runparams_in,
347                                  OutputWhat output = FullSource) const;
348         ///
349         ExportStatus makeLyXHTMLFile(support::FileName const & filename,
350                              OutputParams const & runparams_in) const;
351         ///
352         ExportStatus writeLyXHTMLSource(odocstream & os,
353                              OutputParams const & runparams_in,
354                              OutputWhat output = FullSource) const;
355         /// returns the main language for the buffer (document)
356         Language const * language() const;
357         /// get l10n translated to the buffers language
358         docstring B_(std::string const & l10n) const;
359
360         ///
361         int runChktex();
362         /// return true if the main lyx file does not need saving
363         bool isClean() const;
364         ///
365         bool isDepClean(std::string const & name) const;
366
367         /// Whether or not disk file has been externally modified. Uses a checksum
368         /// which is accurate but slow, which can be a problem when it is frequently
369         /// used, or used for a large file on a slow (network) file system.
370         bool isChecksumModified() const;
371
372         /// Flag set by the FileSystemWatcher.
373         /// Fast but (not so) inaccurate, can be cleared by the user.
374         bool notifiesExternalModification() const;
375         void clearExternalModification() const;
376
377         /// mark the main lyx file as not needing saving
378         void markClean() const;
379
380         ///
381         void markDepClean(std::string const & name);
382
383         ///
384         void setUnnamed(bool flag = true);
385
386         /// Whether or not a filename has been assigned to this buffer
387         bool isUnnamed() const;
388
389         /// Whether or not this buffer is internal.
390         ///
391         /// An internal buffer does not contain a real document, but some auxiliary text segment.
392         /// It is not associated with a filename, it is never saved, thus it does not need to be
393         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
394         bool isInternal() const;
395
396         void setInternal(bool flag);
397
398         /// Mark this buffer as dirty.
399         void markDirty();
400
401         /// Returns the buffer's filename. It is always an absolute path.
402         support::FileName fileName() const;
403
404         /// Returns the buffer's filename. It is always an absolute path.
405         std::string absFileName() const;
406
407         /// Returns the path where the buffer lives.
408         /// It is always an absolute path.
409         std::string filePath() const;
410
411         /** Contructs a file name of a referenced file (child doc, included graphics etc).
412          *  Absolute names are returned as is. If the name is relative, it is
413          *  interpreted relative to filePath() if the file exists, otherwise
414          *  relative to the original path where the document was last saved.
415          *  The original path may be different from filePath() if the document was
416          *  later manually moved to a different location.
417          */
418         support::DocFileName getReferencedFileName(std::string const & fn) const;
419
420         /// Format a file name for LaTeX output (absolute or relative or filename only,
421         /// depending on file and context)
422         std::string const prepareFileNameForLaTeX(std::string const &,
423                                         std::string const &, bool nice) const;
424
425         /** Returns a vector of bibliography (*.bib) file paths suitable for the
426          *  output in the respective BibTeX/Biblatex macro and potential individual encoding
427          */
428         std::vector<std::pair<docstring, std::string>> const prepareBibFilePaths(OutputParams const &,
429                                     const docstring_list & bibfilelist,
430                                     bool const extension = true) const;
431
432         /** Returns the path where a local layout file lives.
433          *  An empty string is returned for standard system and user layouts.
434          *  If possible, it is always relative to the buffer path.
435          */
436         std::string layoutPos() const;
437
438         /** Set the path to a local layout file.
439          *  This must be an absolute path but, if possible, it is always
440          *  stored as relative to the buffer path.
441          */
442         void setLayoutPos(std::string const & path);
443
444         /** A transformed version of the file name, adequate for LaTeX.
445             \param no_path optional if \c true then the path is stripped.
446         */
447         std::string latexName(bool no_path = true) const;
448
449         /// Get the name and type of the log.
450         std::string logName(LogType * type = nullptr) const;
451
452         /// Set document's parent Buffer.
453         void setParent(Buffer const *);
454         Buffer const * parent() const;
455
456         /** Get the document's master (or \c this if this is not a
457             child document)
458          */
459         Buffer const * masterBuffer() const;
460
461         /// \return true if \p child is a child of this \c Buffer.
462         bool isChild(Buffer * child) const;
463
464         /// \return true if this \c Buffer has children
465         bool hasChildren() const;
466
467         /// \return a list of the direct children of this Buffer.
468         /// this list has no duplicates and is in the order in which
469         /// the children appear.
470         ListOfBuffers getChildren() const;
471
472         /// \return a list of all descendants of this Buffer (children,
473         /// grandchildren, etc). this list has no duplicates and is in
474         /// the order in which the children appear.
475         ListOfBuffers getDescendants() const;
476
477         /// Collect all relative buffers, in the order in which they appear.
478         /// I.e., the "root" Buffer is first, then its first child, then any
479         /// of its children, etc. However, there are no duplicates in this
480         /// list.
481         /// This is "stable", too, in the sense that it returns the same
482         /// thing from whichever Buffer it is called.
483         ListOfBuffers allRelatives() const;
484
485         /// Is buffer read-only? True if it has either the read-only flag or the
486         /// externally modified flag.
487         bool isReadonly() const;
488
489         /// Does the buffer have the read-only flag?
490         bool hasReadonlyFlag() const;
491
492         /// Set buffer read-only flag
493         void setReadonly(bool flag = true);
494
495         /** Validate a buffer for LaTeX.
496             This validates the buffer, and returns a struct for use by
497             #makeLaTeX# and others. Its main use is to figure out what
498             commands and packages need to be included in the LaTeX file.
499             It (should) also check that the needed constructs are there
500             (i.e. that the \refs points to coresponding \labels). It
501             should perhaps inset "error" insets to help the user correct
502             obvious mistakes.
503         */
504         void validate(LaTeXFeatures &) const;
505
506         /// Bibliography information is cached in the Buffer, so we do not
507         /// have to check or read things over and over.
508         /// The cache exists only in the master buffer. When it is updated,
509         /// the children add their information to the master's cache.
510         /// Calling this method invalidates the cache and so requires a
511         /// re-read.
512         void invalidateBibinfoCache() const;
513         /// Clear the bibfiles cache
514         void clearBibFileCache() const;
515         /// Updates the cached bibliography information, checking first to see
516         /// whether the cache is valid. If so, we do nothing. If not, then we
517         /// reload all the BibTeX info.
518         /// Note that this operates on the master document.
519         void reloadBibInfoCache(bool const force = false) const;
520         /// \return the bibliography information for this buffer's master,
521         /// or just for it, if it isn't a child.
522         BiblioInfo const & masterBibInfo() const;
523         /// \return this buffer's bibliography information
524         BiblioInfo const & bibInfo() const;
525         /// collect bibliography info from the various insets in this buffer.
526         void collectBibKeys(support::FileNameList &) const;
527         /// add some BiblioInfo to our cache
528         void addBiblioInfo(BiblioInfo const & bi) const;
529         /// add a single piece of bibliography info to our cache
530         void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
531         ///
532         void makeCitationLabels() const;
533         ///
534         void invalidateCiteLabels() const;
535         ///
536         bool citeLabelsValid() const;
537         /// three strings: plain label name, label as gui string, and
538         /// dereferenced label name
539         void getLabelList(std::vector<std::tuple<docstring, docstring, docstring>> &) const;
540
541         /// This removes the .aux and .bbl files from the temp dir.
542         void removeBiblioTempFiles() const;
543
544         ///
545         void changeLanguage(Language const * from, Language const * to);
546
547         ///
548         bool isMultiLingual() const;
549         ///
550         std::set<Language const *> getLanguages() const;
551
552         ///
553         BufferParams & params();
554         BufferParams const & params() const;
555         ///
556         BufferParams const & masterParams() const;
557
558         /** The list of paragraphs.
559             This is a linked list of paragraph, this list holds the
560             whole contents of the document.
561          */
562         ParagraphList & paragraphs();
563         ParagraphList const & paragraphs() const;
564
565         /// LyX version control object.
566         LyXVC & lyxvc();
567         LyXVC const & lyxvc() const;
568
569         /// Where to put temporary files.
570         std::string const temppath() const;
571
572         /// Used when typesetting to place errorboxes.
573         TexRow const & texrow() const;
574         TexRow & texrow();
575
576         ///
577         ParIterator par_iterator_begin();
578         ///
579         ParConstIterator par_iterator_begin() const;
580         ///
581         ParIterator par_iterator_end();
582         ///
583         ParConstIterator par_iterator_end() const;
584         /// Is document empty ?
585         bool empty() const;
586
587         // Position of the child buffer where it appears first in the master.
588         DocIterator firstChildPosition(Buffer const * child);
589
590         /** \returns true only when the file is fully loaded.
591          *  Used to prevent the premature generation of previews
592          *  and by the citation inset.
593          */
594         bool isFullyLoaded() const;
595         /// Set by buffer_funcs' newFile.
596         void setFullyLoaded(bool);
597
598         /// FIXME: Needed by RenderPreview.
599         graphics::PreviewLoader * loader() const;
600         /// Update the LaTeX preview snippets associated with this buffer
601         void updatePreviews() const;
602         /// Remove any previewed LaTeX snippets associated with this buffer
603         void removePreviews() const;
604         ///
605         graphics::Cache & graphicsCache() const;
606
607         /// Our main text (inside the top InsetText)
608         Text & text() const;
609
610         /// Our top InsetText
611         Inset & inset() const;
612
613         //
614         // Macro handling
615         //
616         /// Collect macro definitions in paragraphs
617         void updateMacros() const;
618         /// Iterate through the whole buffer and try to resolve macros
619         void updateMacroInstances(UpdateType) const;
620
621         /// List macro names of this buffer, the parent and the children
622         void listMacroNames(MacroNameSet & macros) const;
623         /// Collect macros of the parent and its children in front of this buffer.
624         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
625
626         /// Return macro defined before pos (or in the master buffer)
627         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
628         /// Return macro defined anywhere in the buffer (or in the master buffer)
629         MacroData const * getMacro(docstring const & name, bool global = true) const;
630         /// Return macro defined before the inclusion of the child
631         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
632
633         /// Collect user macro names at loading time
634         typedef std::set<docstring> UserMacroSet;
635         mutable UserMacroSet usermacros;
636
637         /// Replace the inset contents for insets which InsetCode is equal
638         /// to the passed \p inset_code. Handles undo.
639         void changeRefsIfUnique(docstring const & from, docstring const & to);
640
641         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
642         /// including preamble
643         /// returns nullptr if Id to Row conversion is unsupported
644         unique_ptr<TexRow> getSourceCode(odocstream & os,
645                         std::string const & format, pit_type par_begin,
646                         pit_type par_end, OutputWhat output, bool master) const;
647
648         /// Access to error list.
649         /// This method is used only for GUI visualisation of Buffer related
650         /// errors (like parsing or LateX compilation). This method is const
651         /// because modifying the returned ErrorList does not touch the document
652         /// contents.
653         ErrorList & errorList(std::string const & type) const;
654
655         /// The Toc backend.
656         /// This is useful only for screen visualisation of the Buffer. This
657         /// method is const because modifying this backend does not touch
658         /// the document contents.
659         TocBackend & tocBackend() const;
660
661         ///
662         Undo & undo();
663         ///
664         Undo const & undo() const;
665
666         /// This function is called when the buffer is changed.
667         void changed(bool update_metrics) const;
668         ///
669         void setChild(DocIterator const & dit, Buffer * child);
670         ///
671         void updateTocItem(std::string const &, DocIterator const &) const;
672         /// This function is called when the buffer structure is changed.
673         void structureChanged() const;
674         /// This function is called when some parsing error shows up.
675         void errors(std::string const & err, bool from_master = false) const;
676         /// This function is called when the buffer busy status change.
677         void setBusy(bool on) const;
678         /// Update window titles of all users.
679         void updateTitles() const;
680         /// Schedule redraw of work areas
681         void scheduleRedrawWorkAreas() const;
682         /// Reset autosave timers for all users.
683         void resetAutosaveTimers() const;
684         ///
685         void message(docstring const & msg) const;
686
687         ///
688         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
689         ///
690         bool hasGuiDelegate() const;
691
692         ///
693         ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
694         /// Export buffer to format \p format and open the result in a suitable viewer.
695         /// Note: This has nothing to do with preview of graphics or math formulas.
696         ExportStatus preview(std::string const & format) const;
697         /// true if there was a previous preview this session of this buffer and
698         /// there was an error on the previous preview of this buffer.
699         bool freshStartRequired() const;
700         ///
701         void requireFreshStart(bool const b) const;
702
703 private:
704         ///
705         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
706                 std::string & result_file) const;
707         /// target is a format name optionally followed by a space
708         /// and a destination file-name
709         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
710                 bool includeall, std::string & result_file) const;
711         ///
712         ExportStatus preview(std::string const & format, bool includeall) const;
713         ///
714         void setMathFlavor(OutputParams & op) const;
715
716 public:
717         ///
718         bool isExporting() const;
719
720         /// A collection of InsetRef insets and their position in the buffer
721         typedef std::vector<std::pair<Inset *, ParIterator> > References;
722         /// Get all InsetRef insets and their positions associated with
723         /// the InsetLabel with the label string \p label
724         References const & references(docstring const & label) const;
725         /// Add an InsetRef at position \p it to the Insetlabel
726         /// with the label string \p label
727         void addReference(docstring const & label, Inset * inset, ParIterator it);
728         /// Clear the whole reference cache
729         void clearReferenceCache() const;
730         /// Set the InsetLabel for a given \p label string. \p active
731         /// determines whether this is an active label (see @ref activeLabel)
732         void setInsetLabel(docstring const & label, InsetLabel const * il,
733                            bool const active);
734         /// \return the InsetLabel associated with this \p label string
735         /// If \p active is true we only return active labels
736         /// (see @ref activeLabel)
737         InsetLabel const * insetLabel(docstring const & label,
738                                       bool const active = false) const;
739         /// \return true if this \param label is an active label.
740         /// Inactive labels are currently deleted labels (in ct mode)
741         bool activeLabel(docstring const & label) const;
742
743         /// return a list of all used branches (also in children)
744         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
745
746         /// Updates screen labels and some other information associated with
747         /// insets and paragraphs. Actually, it's more like a general "recurse
748         /// through the Buffer" routine, that visits all the insets and paragraphs.
749         void updateBuffer() const;
750         /// \param scope: whether to start with the master document or just
751         /// do this one.
752         /// \param output: whether we are preparing for output.
753         void updateBuffer(UpdateScope scope, UpdateType utype) const;
754         ///
755         void updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted = false) const;
756         /// Forces an updateBuffer() call
757         void forceUpdate() const;
758         /// Do we need to call updateBuffer()?
759         bool needUpdate() const;
760
761         /// Spellcheck starting from \p from.
762         /// \p from initial position, will then points to the next misspelled
763         ///    word.
764         /// \p to will points to the end of the next misspelled word.
765         /// \p word_lang will contain the found misspelled word.
766         /// \return progress if a new word was found.
767         int spellCheck(DocIterator & from, DocIterator & to,
768                 WordLangTuple & word_lang, docstring_list & suggestions) const;
769         /// Marks the whole buffer to be checked (again)
770         void requestSpellcheck();
771         ///
772         void checkChildBuffers();
773         ///
774         void checkMasterBuffer();
775
776         /// If the document is being saved to a new location and the named file
777         /// exists at the old location, return its updated path relative to the
778         /// new buffer path if possible, otherwise return its absolute path.
779         /// In all other cases, this is a no-op and name is returned unchanged.
780         /// If a non-empty ext is given, the existence of name.ext is checked
781         /// but the returned path will not contain this extension.
782         /// Similarly, when loading a document that was moved from the location
783         /// where it was saved, return the correct path relative to the new
784         /// location.
785         std::string includedFilePath(std::string const & name,
786                                 std::string const & ext = empty_string()) const;
787
788         /// compute statistics between \p from and \p to
789         /// \p from initial position
790         /// \p to points to the end position
791         /// \p skipNoOutput if notes etc. should be ignored
792         void updateStatistics(DocIterator & from, DocIterator & to,
793                                                   bool skipNoOutput = true) const;
794         /// statistics accessor functions
795         int wordCount() const;
796         int charCount(bool with_blanks) const;
797
798         ///
799         bool areChangesPresent() const;
800
801         ///
802         void registerBibfiles(docstring_list const & bf) const;
803         ///
804         support::FileName getBibfilePath(docstring const & bibid) const;
805         /// Return the list with all bibfiles in use (including bibfiles
806         /// of loaded child documents).
807         docstring_list const &
808                 getBibfiles(UpdateScope scope = UpdateMaster) const;
809         ///
810         bool needToRemoveBiblioTemps() const { return removeBiblioTemps; }
811         /// routines for dealing with possible self-inclusion
812         void pushIncludedBuffer(Buffer const * buf) const;
813         void popIncludedBuffer() const;
814         bool isBufferIncluded(Buffer const * buf) const;
815 private:
816         void clearIncludeList() const;
817         ///
818         friend class MarkAsExporting;
819         /// mark the buffer as busy exporting something, or not
820         void setExportStatus(bool e) const;
821         ///
822         mutable bool removeBiblioTemps = false;
823
824         ///
825         References & getReferenceCache(docstring const & label);
826         /// Change name of buffer. Updates "read-only" flag.
827         void setFileName(support::FileName const & fname);
828         ///
829         void getLanguages(std::set<Language const *> &) const;
830         /// Checks whether any of the referenced bibfiles have changed since the
831         /// last time we loaded the cache. Note that this does NOT update the
832         /// cached information.
833         void checkIfBibInfoCacheIsValid() const;
834         ///
835         void collectChildren(ListOfBuffers & children, bool grand_children) const;
836
837         /// noncopyable
838         Buffer(Buffer const &);
839         void operator=(Buffer const &);
840
841         /// Use the Pimpl idiom to hide the internals.
842         class Impl;
843         /// The pointer never changes although *pimpl_'s contents may.
844         Impl * const d;
845 };
846
847
848 /// Helper class, to guarantee that the export status
849 /// gets reset properly. To use, simply create a local variable:
850 ///    MarkAsExporting mex(bufptr);
851 /// and leave the rest to us.
852 class MarkAsExporting {
853 public:
854         MarkAsExporting(Buffer const * buf) : buf_(buf)
855         {
856                 buf_->setExportStatus(true);
857         }
858         ~MarkAsExporting()
859         {
860                 buf_->setExportStatus(false);
861         }
862 private:
863         Buffer const * const buf_;
864 };
865
866
867 } // namespace lyx
868
869 #endif