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