]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
8b5465c673d2a2979f5747bd5290f71926ca173d
[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 "OutputEnums.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21
22 #include <list>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class DispatchResult;
33 class DocIterator;
34 class docstring_list;
35 class ErrorList;
36 class FuncRequest;
37 class FuncStatus;
38 class Inset;
39 class InsetLabel;
40 class InsetRef;
41 class Font;
42 class Format;
43 class Lexer;
44 class Text;
45 class LyXVC;
46 class LaTeXFeatures;
47 class Language;
48 class MacroData;
49 class MacroNameSet;
50 class MacroSet;
51 class OutputParams;
52 class Paragraph;
53 class ParConstIterator;
54 class ParIterator;
55 class ParagraphList;
56 class TeXErrors;
57 class TexRow;
58 class TocBackend;
59 class Undo;
60 class WordLangTuple;
61
62 namespace frontend {
63 class GuiBufferDelegate;
64 class WorkAreaManager;
65 }
66
67 namespace support {
68 class FileName;
69 class FileNameList;
70 }
71
72
73 class Buffer;
74 typedef std::list<Buffer *> ListOfBuffers;
75
76
77 /** The buffer object.
78  * This is the buffer object. It contains all the informations about
79  * a document loaded into LyX.
80  * The buffer object owns the Text (wrapped in an InsetText), which
81  * contains the individual paragraphs of the document.
82  *
83  *
84  * I am not sure if the class is complete or
85  * minimal, probably not.
86  * \author Lars Gullik Bjønnes
87  */
88 class Buffer {
89 public:
90         /// What type of log will \c getLogName() return?
91         enum LogType {
92                 latexlog, ///< LaTeX log
93                 buildlog  ///< Literate build log
94         };
95
96         /// Result of \c readFile()
97         enum ReadStatus {
98                 failure, ///< The file could not be read
99                 success, ///< The file could not be read
100                 wrongversion ///< The version of the file does not match ours
101         };
102
103
104         /// Method to check if a file is externally modified, used by
105         /// isExternallyModified()
106         /**
107          * timestamp is fast but inaccurate. For example, the granularity
108          * of timestamp on a FAT filesystem is 2 second. Also, various operations
109          * may touch the timestamp of a file even when its content is unchanged.
110          *
111          * checksum is accurate but slow, which can be a problem when it is
112          * frequently used, or used for a large file on a slow (network) file
113          * system.
114          *
115          * FIXME: replace this method with support/FileMonitor.
116          */
117         enum CheckMethod {
118                 checksum_method,  ///< Use file checksum
119                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
120         };
121
122         ///
123         enum UpdateScope {
124                 UpdateMaster,
125                 UpdateChildOnly
126         };
127
128         /// Constructor
129         explicit Buffer(std::string const & file, bool readonly = false,
130                 Buffer const * cloned_buffer = 0);
131
132         /// Destructor
133         ~Buffer();
134
135         ///
136         Buffer * clone() const;
137         ///
138         bool isClone() const;
139
140         /** High-level interface to buffer functionality.
141             This function parses a command string and executes it.
142         */
143         void dispatch(std::string const & command, DispatchResult & result);
144
145         /// Maybe we know the function already by number...
146         void dispatch(FuncRequest const & func, DispatchResult & result);
147
148         /// Can this function be exectued?
149         /// \return true if we made a decision
150         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
151
152         /// read a new document from a string
153         bool readString(std::string const &);
154         /// load a new file
155         bool readFile(support::FileName const & filename);
156
157         /// read the header, returns number of unknown tokens
158         int readHeader(Lexer & lex);
159
160         /** Reads a file without header.
161             \param par if != 0 insert the file.
162             \return \c true if file is not completely read.
163         */
164         bool readDocument(Lexer &);
165
166         ///
167         DocIterator getParFromID(int id) const;
168         /// do we have a paragraph with this id?
169         bool hasParWithID(int id) const;
170
171         ///
172         frontend::WorkAreaManager & workAreaManager() const;
173
174         /** Save file.
175             Takes care of auto-save files and backup file if requested.
176             Returns \c true if the save is successful, \c false otherwise.
177         */
178         bool save() const;
179
180         /// Write document to stream. Returns \c false if unsuccesful.
181         bool write(std::ostream &) const;
182         /// save emergency file
183         /// \return a status message towards the user.
184         docstring emergencyWrite();
185         /// Write file. Returns \c false if unsuccesful.
186         bool writeFile(support::FileName const &) const;
187
188         /// Loads LyX file \c filename into buffer, *  and return success
189         bool loadLyXFile(support::FileName const & s);
190         /// Reloads the LyX file
191         bool reload();
192
193         /// Fill in the ErrorList with the TeXErrors
194         void bufferErrors(TeXErrors const &, ErrorList &) const;
195
196         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
197         bool makeLaTeXFile(support::FileName const & filename,
198                            std::string const & original_path,
199                            OutputParams const &,
200                            bool output_preamble = true,
201                            bool output_body = true) const;
202         /** Export the buffer to LaTeX.
203             If \p os is a file stream, and params().inputenc is "auto" or
204             "default", and the buffer contains text in different languages
205             with more than one encoding, then this method will change the
206             encoding associated to \p os. Therefore you must not call this
207             method with a string stream if the output is supposed to go to a
208             file. \code
209             ofdocstream ofs;
210             ofs.open("test.tex");
211             writeLaTeXSource(ofs, ...);
212             ofs.close();
213             \endcode is NOT equivalent to \code
214             odocstringstream oss;
215             writeLaTeXSource(oss, ...);
216             ofdocstream ofs;
217             ofs.open("test.tex");
218             ofs << oss.str();
219             ofs.close();
220             \endcode
221          */
222         void writeLaTeXSource(odocstream & os,
223                            std::string const & original_path,
224                            OutputParams const &,
225                            bool output_preamble = true,
226                            bool output_body = true) const;
227         ///
228         void makeDocBookFile(support::FileName const & filename,
229                              OutputParams const & runparams_in,
230                              bool only_body = false) const;
231         ///
232         void writeDocBookSource(odocstream & os, std::string const & filename,
233                              OutputParams const & runparams_in,
234                              bool only_body = false) const;
235         ///
236         void makeLyXHTMLFile(support::FileName const & filename,
237                              OutputParams const & runparams_in,
238                              bool only_body = false) const;
239         ///
240         void writeLyXHTMLSource(odocstream & os,
241                              OutputParams const & runparams_in,
242                              bool only_body = false) const;
243         /// returns the main language for the buffer (document)
244         Language const * language() const;
245         /// get l10n translated to the buffers language
246         docstring const B_(std::string const & l10n) const;
247
248         ///
249         int runChktex();
250         /// return true if the main lyx file does not need saving
251         bool isClean() const;
252         ///
253         bool isDepClean(std::string const & name) const;
254
255         /// whether or not disk file has been externally modified
256         bool isExternallyModified(CheckMethod method) const;
257
258         /// save timestamp and checksum of the given file.
259         void saveCheckSum(support::FileName const & file) const;
260
261         /// mark the main lyx file as not needing saving
262         void markClean() const;
263
264         ///
265         void markDepClean(std::string const & name);
266
267         ///
268         void setUnnamed(bool flag = true);
269
270         /// Whether or not a filename has been assigned to this buffer
271         bool isUnnamed() const;
272
273         /// Whether or not this buffer is internal.
274         ///
275         /// An internal buffer does not contain a real document, but some auxiliary text segment.
276         /// It is not associated with a filename, it is never saved, thus it does not need to be
277         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
278         bool isInternal() const;
279
280         /// Mark this buffer as dirty.
281         void markDirty();
282
283         /// Returns the buffer's filename. It is always an absolute path.
284         support::FileName fileName() const;
285
286         /// Returns the buffer's filename. It is always an absolute path.
287         std::string absFileName() const;
288
289         /// Returns the the path where the buffer lives.
290         /// It is always an absolute path.
291         std::string filePath() const;
292
293         /** A transformed version of the file name, adequate for LaTeX.
294             \param no_path optional if \c true then the path is stripped.
295         */
296         std::string latexName(bool no_path = true) const;
297
298         /// Get the name and type of the log.
299         std::string logName(LogType * type = 0) const;
300
301         /// Change name of buffer. Updates "read-only" flag.
302         void setFileName(std::string const & newfile);
303
304         /// Set document's parent Buffer.
305         void setParent(Buffer const *);
306         Buffer const * parent() const;
307
308         /// Collect all relative buffers, in the order in which they appear.
309         /// I.e., the "root" Buffer is first, then its first child, then any
310         /// of its children, etc. However, there are no duplicates in this
311         /// list.
312         /// This is "stable", too, in the sense that it returns the same
313         /// thing from whichever Buffer it is called.
314         ListOfBuffers allRelatives() const;
315
316         /** Get the document's master (or \c this if this is not a
317             child document)
318          */
319         Buffer const * masterBuffer() const;
320
321         /// \return true if \p child is a child of this \c Buffer.
322         bool isChild(Buffer * child) const;
323         
324         /// \return true if this \c Buffer has children
325         bool hasChildren() const;
326         
327         /// return a vector of all children (and grandchildren)
328         ListOfBuffers getChildren(bool grand_children = true) const;
329
330         /// Add all children (and grandchildren) to supplied vector
331         void getChildren(ListOfBuffers & children, bool grand_children = true) const;
332
333         /// Is buffer read-only?
334         bool isReadonly() const;
335
336         /// Set buffer read-only flag
337         void setReadonly(bool flag = true);
338
339         /// returns \c true if the buffer contains a LaTeX document
340         bool isLatex() const;
341         /// returns \c true if the buffer contains a DocBook document
342         bool isDocBook() const;
343         /// returns \c true if the buffer contains a Wed document
344         bool isLiterate() const;
345
346         /** Validate a buffer for LaTeX.
347             This validates the buffer, and returns a struct for use by
348             #makeLaTeX# and others. Its main use is to figure out what
349             commands and packages need to be included in the LaTeX file.
350             It (should) also check that the needed constructs are there
351             (i.e. that the \refs points to coresponding \labels). It
352             should perhaps inset "error" insets to help the user correct
353             obvious mistakes.
354         */
355         void validate(LaTeXFeatures &) const;
356
357         /// Reference information is cached in the Buffer, so we do not
358         /// have to check or read things over and over. 
359         ///
360         /// There are two caches.
361         ///
362         /// One is a cache of the BibTeX files from which reference info is
363         /// being gathered. This cache is PER BUFFER, and the cache for the
364         /// master essentially includes the cache for its children. This gets
365         /// invalidated when an InsetBibtex is created, deleted, or modified.
366         /// 
367         /// The other is a cache of the reference information itself. This
368         /// exists only in the master buffer, and when it needs to be updated,
369         /// the children add their information to the master's cache.
370         
371         /// Calling this method invalidates the cache and so requires a
372         /// re-read.
373         void invalidateBibinfoCache() const;
374         /// This invalidates the cache of files we need to check.
375         void invalidateBibfileCache() const;
376         /// Updates the cached bibliography information.
377         /// Note that you MUST call this method to update the cache. It will
378         /// not happen otherwise. (Currently, it is called at the start of
379         /// updateBuffer() and from GuiCitation.)
380         /// Note that this operates on the master document.
381         void checkBibInfoCache() const;
382         /// \return the bibliography information for this buffer's master,
383         /// or just for it, if it isn't a child.
384         BiblioInfo const & masterBibInfo() const;
385         ///
386         void fillWithBibKeys(BiblioInfo & keys) const;
387         ///
388         void getLabelList(std::vector<docstring> &) const;
389
390         ///
391         void changeLanguage(Language const * from, Language const * to);
392
393         ///
394         bool isMultiLingual() const;
395         ///
396         std::set<Language const *> getLanguages() const;
397
398         ///
399         BufferParams & params();
400         BufferParams const & params() const;
401
402         /** The list of paragraphs.
403             This is a linked list of paragraph, this list holds the
404             whole contents of the document.
405          */
406         ParagraphList & paragraphs();
407         ParagraphList const & paragraphs() const;
408
409         /// LyX version control object.
410         LyXVC & lyxvc();
411         LyXVC const & lyxvc() const;
412
413         /// Where to put temporary files.
414         std::string const temppath() const;
415
416         /// Used when typesetting to place errorboxes.
417         TexRow const & texrow() const;
418         TexRow & texrow();
419
420         ///
421         ParIterator par_iterator_begin();
422         ///
423         ParConstIterator par_iterator_begin() const;
424         ///
425         ParIterator par_iterator_end();
426         ///
427         ParConstIterator par_iterator_end() const;
428
429         // Position of the child buffer where it appears first in the master.
430         DocIterator firstChildPosition(Buffer const * child);
431
432         /** \returns true only when the file is fully loaded.
433          *  Used to prevent the premature generation of previews
434          *  and by the citation inset.
435          */
436         bool isFullyLoaded() const;
437         /// Set by buffer_funcs' newFile.
438         void setFullyLoaded(bool);
439
440         /// Our main text (inside the top InsetText)
441         Text & text() const;
442
443         /// Our top InsetText
444         Inset & inset() const;
445
446         //
447         // Macro handling
448         //
449         /// Collect macro definitions in paragraphs
450         void updateMacros() const;
451         /// Iterate through the whole buffer and try to resolve macros
452         void updateMacroInstances() const;
453
454         /// List macro names of this buffer, the parent and the children
455         void listMacroNames(MacroNameSet & macros) const;
456         /// Collect macros of the parent and its children in front of this buffer.
457         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
458
459         /// Return macro defined before pos (or in the master buffer)
460         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
461         /// Return macro defined anywhere in the buffer (or in the master buffer)
462         MacroData const * getMacro(docstring const & name, bool global = true) const;
463         /// Return macro defined before the inclusion of the child
464         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
465
466         /// Collect user macro names at loading time
467         typedef std::set<docstring> UserMacroSet;
468         UserMacroSet usermacros;
469
470         /// Replace the inset contents for insets which InsetCode is equal
471         /// to the passed \p inset_code.
472         void changeRefsIfUnique(docstring const & from, docstring const & to,
473                 InsetCode code);
474
475         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
476         /// including preamble
477         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
478                 bool full_source) const;
479
480         /// Access to error list.
481         /// This method is used only for GUI visualisation of Buffer related
482         /// errors (like parsing or LateX compilation). This method is const
483         /// because modifying the returned ErrorList does not touch the document
484         /// contents.
485         ErrorList & errorList(std::string const & type) const;
486
487         /// The Toc backend.
488         /// This is useful only for screen visualisation of the Buffer. This
489         /// method is const because modifying this backend does not touch
490         /// the document contents.
491         TocBackend & tocBackend() const;
492
493         ///
494         Undo & undo();
495
496         /// This function is called when the buffer is changed.
497         void changed(bool update_metrics) const;
498         ///
499         void setChild(DocIterator const & dit, Buffer * child);
500         ///
501         void updateTocItem(std::string const &, DocIterator const &) const;
502         /// This function is called when the buffer structure is changed.
503         void structureChanged() const;
504         /// This function is called when some parsing error shows up.
505         void errors(std::string const & err, bool from_master = false) const;
506         /// This function is called when the buffer busy status change.
507         void setBusy(bool on) const;
508         /// Update window titles of all users.
509         void updateTitles() const;
510         /// Reset autosave timers for all users.
511         void resetAutosaveTimers() const;
512         ///
513         void message(docstring const & msg) const;
514
515         ///
516         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
517         ///
518         bool hasGuiDelegate() const;
519
520         ///
521         void autoSave() const;
522         ///
523         void removeAutosaveFile() const;
524         ///
525         void moveAutosaveFile(support::FileName const & old) const;
526         ///
527         support::FileName getAutosaveFileName() const;
528
529         /// return the format of the buffer on a string
530         std::string bufferFormat() const;
531         /// return the default output format of the current backend
532         std::string getDefaultOutputFormat() const;
533
534         ///
535         bool doExport(std::string const & format, bool put_in_tempdir,
536                 bool includeall, std::string & result_file) const;
537         ///
538         bool doExport(std::string const & format, bool put_in_tempdir,
539                       bool includeall = false) const;
540         ///
541         bool preview(std::string const & format, bool includeall = false) const;
542         ///
543         bool isExportable(std::string const & format) const;
544         ///
545         std::vector<Format const *> exportableFormats(bool only_viewable) const;
546         ///
547         bool isExportableFormat(std::string const & format) const;
548         /// mark the buffer as busy exporting something, or not
549         void setExportStatus(bool e) const;
550         ///
551         bool isExporting() const;
552
553         ///
554         typedef std::vector<std::pair<Inset *, ParIterator> > References;
555         References & references(docstring const & label);
556         References const & references(docstring const & label) const;
557         void clearReferenceCache() const;
558         void setInsetLabel(docstring const & label, InsetLabel const * il);
559         InsetLabel const * insetLabel(docstring const & label) const;
560
561         /// return a list of all used branches (also in children)
562         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
563
564         /// sets the buffer_ member for every inset in this buffer.
565         // FIXME This really shouldn't be needed, but at the moment it's not
566         // clear how to do it just for the individual pieces we need.
567         void setBuffersForInsets() const;
568         /// Updates screen labels and some other information associated with
569         /// insets and paragraphs. Actually, it's more like a general "recurse
570         /// through the Buffer" routine, that visits all the insets and paragraphs.
571         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
572         /// \param scope: whether to start with the master document or just
573         /// do this one.
574         /// \param output: whether we are preparing for output.
575         void updateBuffer(UpdateScope scope, UpdateType utype) const;
576         /// 
577         void updateBuffer(ParIterator & parit, UpdateType utype) const;
578
579         /// Spellcheck starting from \p from.
580         /// \p from initial position, will then points to the next misspelled
581         ///    word.
582         /// \p to will points to the end of the next misspelled word.
583         /// \p word_lang will contain the found misspelled word.
584         /// \return progress if a new word was found.
585         int spellCheck(DocIterator & from, DocIterator & to,
586                 WordLangTuple & word_lang, docstring_list & suggestions) const;
587         ///
588         void checkChildBuffers();
589
590 private:
591         ///
592         bool readFileHelper(support::FileName const & s);
593         ///
594         std::vector<std::string> backends() const;
595         /** Inserts a file into a document
596             \return \c false if method fails.
597         */
598         ReadStatus readFile(Lexer &, support::FileName const & filename,
599                             bool fromString = false);
600         ///
601         void getLanguages(std::set<Language const *> &) const;
602         /// Update the list of all bibfiles in use (including bibfiles
603         /// of loaded child documents).
604         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
605         /// Return the list with all bibfiles in use (including bibfiles
606         /// of loaded child documents).
607         support::FileNameList const & 
608                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
609
610         /// Use the Pimpl idiom to hide the internals.
611         class Impl;
612         /// The pointer never changes although *pimpl_'s contents may.
613         Impl * const d;
614 };
615
616
617 } // namespace lyx
618
619 #endif