]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Move Lexer to support/ directory (and lyx::support namespace)
[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 Text;
43 class LyXVC;
44 class LaTeXFeatures;
45 class Language;
46 class MacroData;
47 class MacroNameSet;
48 class MacroSet;
49 class OutputParams;
50 class otexstream;
51 class ParagraphList;
52 class ParIterator;
53 class ParConstIterator;
54 class TeXErrors;
55 class TexRow;
56 class TocBackend;
57 class Undo;
58 class WordLangTuple;
59
60 namespace frontend {
61 class GuiBufferDelegate;
62 class WorkAreaManager;
63 } // namespace frontend
64
65 namespace support {
66 class DocFileName;
67 class FileName;
68 class FileNameList;
69 class Lexer;
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(support::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(support::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(support::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         ///
542         void changeLanguage(Language const * from, Language const * to);
543
544         ///
545         bool isMultiLingual() const;
546         ///
547         std::set<Language const *> getLanguages() const;
548
549         ///
550         BufferParams & params();
551         BufferParams const & params() const;
552         ///
553         BufferParams const & masterParams() const;
554
555         /** The list of paragraphs.
556             This is a linked list of paragraph, this list holds the
557             whole contents of the document.
558          */
559         ParagraphList & paragraphs();
560         ParagraphList const & paragraphs() const;
561
562         /// LyX version control object.
563         LyXVC & lyxvc();
564         LyXVC const & lyxvc() const;
565
566         /// Where to put temporary files.
567         std::string const temppath() const;
568
569         /// Used when typesetting to place errorboxes.
570         TexRow const & texrow() const;
571         TexRow & texrow();
572
573         ///
574         ParIterator par_iterator_begin();
575         ///
576         ParConstIterator par_iterator_begin() const;
577         ///
578         ParIterator par_iterator_end();
579         ///
580         ParConstIterator par_iterator_end() const;
581         /// Is document empty ?
582         bool empty() const;
583
584         // Position of the child buffer where it appears first in the master.
585         DocIterator firstChildPosition(Buffer const * child);
586
587         /** \returns true only when the file is fully loaded.
588          *  Used to prevent the premature generation of previews
589          *  and by the citation inset.
590          */
591         bool isFullyLoaded() const;
592         /// Set by buffer_funcs' newFile.
593         void setFullyLoaded(bool);
594
595         /// FIXME: Needed by RenderPreview.
596         graphics::PreviewLoader * loader() const;
597         /// Update the LaTeX preview snippets associated with this buffer
598         void updatePreviews() const;
599         /// Remove any previewed LaTeX snippets associated with this buffer
600         void removePreviews() const;
601         ///
602         graphics::Cache & graphicsCache() const;
603
604         /// Our main text (inside the top InsetText)
605         Text & text() const;
606
607         /// Our top InsetText
608         Inset & inset() const;
609
610         //
611         // Macro handling
612         //
613         /// Collect macro definitions in paragraphs
614         void updateMacros() const;
615         /// Iterate through the whole buffer and try to resolve macros
616         void updateMacroInstances(UpdateType) const;
617
618         /// List macro names of this buffer, the parent and the children
619         void listMacroNames(MacroNameSet & macros) const;
620         /// Collect macros of the parent and its children in front of this buffer.
621         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
622
623         /// Return macro defined before pos (or in the master buffer)
624         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
625         /// Return macro defined anywhere in the buffer (or in the master buffer)
626         MacroData const * getMacro(docstring const & name, bool global = true) const;
627         /// Return macro defined before the inclusion of the child
628         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
629
630         /// Collect user macro names at loading time
631         typedef std::set<docstring> UserMacroSet;
632         mutable UserMacroSet usermacros;
633
634         /// Replace the inset contents for insets which InsetCode is equal
635         /// to the passed \p inset_code. Handles undo.
636         void changeRefsIfUnique(docstring const & from, docstring const & to);
637
638         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
639         /// including preamble
640         /// returns nullptr if Id to Row conversion is unsupported
641         unique_ptr<TexRow> getSourceCode(odocstream & os,
642                         std::string const & format, pit_type par_begin,
643                         pit_type par_end, OutputWhat output, bool master) const;
644
645         /// Access to error list.
646         /// This method is used only for GUI visualisation of Buffer related
647         /// errors (like parsing or LateX compilation). This method is const
648         /// because modifying the returned ErrorList does not touch the document
649         /// contents.
650         ErrorList & errorList(std::string const & type) const;
651
652         /// The Toc backend.
653         /// This is useful only for screen visualisation of the Buffer. This
654         /// method is const because modifying this backend does not touch
655         /// the document contents.
656         TocBackend & tocBackend() const;
657
658         ///
659         Undo & undo();
660         ///
661         Undo const & undo() const;
662
663         /// This function is called when the buffer is changed.
664         void changed(bool update_metrics) const;
665         ///
666         void setChild(DocIterator const & dit, Buffer * child);
667         ///
668         void updateTocItem(std::string const &, DocIterator const &) const;
669         /// This function is called when the buffer structure is changed.
670         void structureChanged() const;
671         /// This function is called when some parsing error shows up.
672         void errors(std::string const & err, bool from_master = false) const;
673         /// This function is called when the buffer busy status change.
674         void setBusy(bool on) const;
675         /// Update window titles of all users.
676         void updateTitles() const;
677         /// Schedule redraw of work areas
678         void scheduleRedrawWorkAreas() const;
679         /// Reset autosave timers for all users.
680         void resetAutosaveTimers() const;
681         ///
682         void message(docstring const & msg) const;
683
684         ///
685         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
686         ///
687         bool hasGuiDelegate() const;
688
689         ///
690         ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
691         /// Export buffer to format \p format and open the result in a suitable viewer.
692         /// Note: This has nothing to do with preview of graphics or math formulas.
693         ExportStatus preview(std::string const & format) const;
694         /// true if there was a previous preview this session of this buffer and
695         /// there was an error on the previous preview of this buffer.
696         bool freshStartRequired() const;
697         ///
698         void requireFreshStart(bool const b) const;
699
700 private:
701         ///
702         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
703                 std::string & result_file) const;
704         /// This removes the .aux and .bbl files from the temp dir.
705         void removeBiblioTempFiles() const;
706         /// target is a format name optionally followed by a space
707         /// and a destination file-name
708         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
709                 bool includeall, std::string & result_file) const;
710         ///
711         ExportStatus preview(std::string const & format, bool includeall) const;
712         ///
713         void setMathFlavor(OutputParams & op) const;
714
715 public:
716         ///
717         bool isExporting() const;
718
719         /// A collection of InsetRef insets and their position in the buffer
720         typedef std::vector<std::pair<Inset *, ParIterator> > References;
721         /// Get all InsetRef insets and their positions associated with
722         /// the InsetLabel with the label string \p label
723         References const & references(docstring const & label) const;
724         /// Add an InsetRef at position \p it to the Insetlabel
725         /// with the label string \p label
726         void addReference(docstring const & label, Inset * inset, ParIterator it);
727         /// Clear the whole reference cache
728         void clearReferenceCache() const;
729         /// Set the InsetLabel for a given \p label string. \p active
730         /// determines whether this is an active label (see @ref activeLabel)
731         void setInsetLabel(docstring const & label, InsetLabel const * il,
732                            bool const active);
733         /// \return the InsetLabel associated with this \p label string
734         /// If \p active is true we only return active labels
735         /// (see @ref activeLabel)
736         InsetLabel const * insetLabel(docstring const & label,
737                                       bool const active = false) const;
738         /// \return true if this \param label is an active label.
739         /// Inactive labels are currently deleted labels (in ct mode)
740         bool activeLabel(docstring const & label) const;
741
742         /// return a list of all used branches (also in children)
743         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
744
745         /// Updates screen labels and some other information associated with
746         /// insets and paragraphs. Actually, it's more like a general "recurse
747         /// through the Buffer" routine, that visits all the insets and paragraphs.
748         void updateBuffer() const;
749         /// \param scope: whether to start with the master document or just
750         /// do this one.
751         /// \param output: whether we are preparing for output.
752         void updateBuffer(UpdateScope scope, UpdateType utype) const;
753         ///
754         void updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted = false) const;
755         /// Forces an updateBuffer() call
756         void forceUpdate() const;
757         /// Do we need to call updateBuffer()?
758         bool needUpdate() const;
759
760         /// Spellcheck starting from \p from.
761         /// \p from initial position, will then points to the next misspelled
762         ///    word.
763         /// \p to will points to the end of the next misspelled word.
764         /// \p word_lang will contain the found misspelled word.
765         /// \return progress if a new word was found.
766         int spellCheck(DocIterator & from, DocIterator & to,
767                 WordLangTuple & word_lang, docstring_list & suggestions) const;
768         /// Marks the whole buffer to be checked (again)
769         void requestSpellcheck();
770         ///
771         void checkChildBuffers();
772         ///
773         void checkMasterBuffer();
774
775         /// If the document is being saved to a new location and the named file
776         /// exists at the old location, return its updated path relative to the
777         /// new buffer path if possible, otherwise return its absolute path.
778         /// In all other cases, this is a no-op and name is returned unchanged.
779         /// If a non-empty ext is given, the existence of name.ext is checked
780         /// but the returned path will not contain this extension.
781         /// Similarly, when loading a document that was moved from the location
782         /// where it was saved, return the correct path relative to the new
783         /// location.
784         std::string includedFilePath(std::string const & name,
785                                 std::string const & ext = empty_string()) const;
786
787         /// compute statistics between \p from and \p to
788         /// \p from initial position
789         /// \p to points to the end position
790         /// \p skipNoOutput if notes etc. should be ignored
791         void updateStatistics(DocIterator & from, DocIterator & to,
792                                                   bool skipNoOutput = true) const;
793         /// statistics accessor functions
794         int wordCount() const;
795         int charCount(bool with_blanks) const;
796
797         ///
798         bool areChangesPresent() const;
799
800         ///
801         void registerBibfiles(docstring_list const & bf) const;
802         ///
803         support::FileName getBibfilePath(docstring const & bibid) const;
804         /// Return the list with all bibfiles in use (including bibfiles
805         /// of loaded child documents).
806         docstring_list const &
807                 getBibfiles(UpdateScope scope = UpdateMaster) const;
808         ///
809         void scheduleBiblioTempRemoval() const { removeBiblioTemps = true; }
810         /// routines for dealing with possible self-inclusion
811         void pushIncludedBuffer(Buffer const * buf) const;
812         void popIncludedBuffer() const;
813         bool isBufferIncluded(Buffer const * buf) const;
814 private:
815         void clearIncludeList() const;
816         ///
817         friend class MarkAsExporting;
818         /// mark the buffer as busy exporting something, or not
819         void setExportStatus(bool e) const;
820         ///
821         mutable bool removeBiblioTemps = false;
822
823         ///
824         References & getReferenceCache(docstring const & label);
825         /// Change name of buffer. Updates "read-only" flag.
826         void setFileName(support::FileName const & fname);
827         ///
828         void getLanguages(std::set<Language const *> &) const;
829         /// Checks whether any of the referenced bibfiles have changed since the
830         /// last time we loaded the cache. Note that this does NOT update the
831         /// cached information.
832         void checkIfBibInfoCacheIsValid() const;
833         ///
834         void collectChildren(ListOfBuffers & children, bool grand_children) const;
835
836         /// noncopyable
837         Buffer(Buffer const &);
838         void operator=(Buffer const &);
839
840         /// Use the Pimpl idiom to hide the internals.
841         class Impl;
842         /// The pointer never changes although *pimpl_'s contents may.
843         Impl * const d;
844 };
845
846
847 /// Helper class, to guarantee that the export status
848 /// gets reset properly. To use, simply create a local variable:
849 ///    MarkAsExporting mex(bufptr);
850 /// and leave the rest to us.
851 class MarkAsExporting {
852 public:
853         MarkAsExporting(Buffer const * buf) : buf_(buf)
854         {
855                 buf_->setExportStatus(true);
856         }
857         ~MarkAsExporting()
858         {
859                 buf_->setExportStatus(false);
860         }
861 private:
862         Buffer const * const buf_;
863 };
864
865
866 } // namespace lyx
867
868 #endif