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