Now that we have a program that can display the contents of a file directly to the screen, it’s time to start adding pagination. In this section, we’ll update our program so that we can scroll forward through the contents of a file one page at a time. We need to let the user scroll at their own speed, so we’ll let them press the spacebar to advance one page forward through the document. When they scroll past the last page of the document we should exit the program. We also want to let the user exit the program earlier if they find what they are looking for, so we’ll let them press the q key at any point while they are scrolling through the document to quit immediately.
You probably already have an intuitive idea for what we mean when we talk about a “page of text,” but as we’re working on implementing pagination it’ll help us to think more carefully about what a page of text is in the context of our application. We’re not going to do any raw or low-level terminal IO, so we’ll be working with individual lines of text. Most terminal emulators have some notion of a dimension measured in a number of rows and columns of fixed-width characters. When we are doing normal high-level terminal IO, each row of text corresponds to a line of printed output, and each line of output can have as many characters as the terminal has columns. If a line of text has more characters than there are columns in the terminal, most terminal emulators will do their own word wrapping. Terminal word wrapping means that our program will have fewer visible lines of text available, since some of the rows will have been taken up by wrapped lines, so we will need to manually track the wrapping in our program to avoid bugs.
When we put all of this togther, we can think of a page of text as a collection of lines of text, each of which are at most some fixed number of characters long.
Let’s start by writing a function to group the lines of text into individual pages. We’ll call our function groupsOf . In order to group our lines of text into pages, we need two things. First, we need to know how many lines of text there are on a page. Second, we need a list of the lines of text that we want to group into pages. We’ll represent a page of text as a list of lines on that page, and we’ll return a list of pages, so the return type of our function will be a list of lists of lines of text.
If we picked a concrete type for our function, we could end up with a type like:
| | groupsOf :: Int -> [ Text . Text ] -> [[ Text . Text ]] |
Of course we might very well want to re-use this code to work with String values, or some other type of text, so we’ll use a polymorphic type:
| | groupsOf :: Int -> [a] -> [[a]] |
The algorithm that we’re going to use to group the pages together is pretty straightforward. The splitAt function from Prelude will do the heavy lifting for us. This function takes a number, n and a list, l , and returns a tuple containing the first n elements of l and the remainder of the elements. We can see this in action in ghci :
| | λ splitAt 0 [1..10] |
| | ( [] ,[1,2,3,4,5,6,7,8,9,10]) |
| | λ splitAt 5 [1..10] |
| | ([1,2,3,4,5],[6,7,8,9,10]) |
| | λ splitAt 9 [1..10] |
| | ([1,2,3,4,5,6,7,8,9],[10]) |
| | λ splitAt 20 [1..10] |
| | ([1,2,3,4,5,6,7,8,9,10], [] ) |
You can see from this example that, thankfully, splitAt handles the case where we want to split at a point past the end of the list by just returning all of the elements in the first element of the tuple, and an empty list in the second element. This will simplify our code quite a bit.
Let’s start writing our groupsOf function by looking at the base case: an empty list. If we don’t have any text to show, our list of pages of text will also be empty:
| | groupsOf :: Int -> [a] -> [[a]] |
| | groupsOf n [] = [] |
Next let’s define the recursive case. We can think of the recursive definition of our function like this: our paginated text is a page made up of the first n lines of text, and the rest of the pages are the result of paginating the remainder of the text:
| | groupsOf n elems = |
| | let (hd, tl) = splitAt n elems |
| | in hd : groupsOf n tl |
Let’s open up ghci and test this out to make sure it works like we expect:
| | λ groupsOf 3 [1,2,3] |
| | [[1,2,3]] |
| | λ groupsOf 3 [1,2,3,4,5,6] |
| | [[1,2,3],[4,5,6]] |
| | λ groupsOf 3 [1,2,3,4,5,6,7] |
| | [[1,2,3],[4,5,6],[7]] |
| | λ groupsOf 10 [1,2,3,4,5,6,7] |
| | [[1,2,3,4,5,6,7]] |
There’s one edge case here that we haven’t tested: if we try to create groups of size zero, our function will return an infinite list of empty lists. This behavior makes sense; a group of size zero is an infinite list, and if we’re never consuming any elements of the input list then we’ll never complete the process of paginating it. You have a couple of options to deal with this. You can choose to leave the behavior as is, pattern match and return an empty list if the group size is zero, make the function a partial function and error to return an error if the caller tries to pass in a group size of zero, or you could change the type of the function to something like this:
| | groupsOf :: Int -> [a] -> Maybe [[a]] |
Throughout this chapter, we’ll stick with the definition of the function as is, but you are encouraged to experiment with other ways of writing this and see if you find one that you like better.
Word Wrapping
Now we have a function that can group lines of text into pages, but it doesn’t account for the fact that any given input string that it gets could be wider than the terminal that we want to write to, leading to word wrapping. The next thing that we’ll need to do is write something that will let us wrap a string, or a Text in our case, so that it takes as many lines as needed to fit into the available width.
We’ll implement word wrapping by adding a new function named wordWrap . The function will take in the maximum width of a line of text, in characters, and will return a list of rows of text that are each at most that length. The type of our function will be:
| | wordWrap :: Int -> Text . Text -> [ Text . Text ] |
We’ll start by writing a “hard-wrapping” algorithm. This will simply break apart lines of text at the maximum line length without respect for word boundaries. The base case for this function will be when the length of the line of text we have is less than, or equal to, the maximum length of a line. In that case, our word-wrapped line of text will just be a single-element list containing the original line of text:
| | wordWrap :: Int -> Text . Text -> [ Text . Text ] |
| | wordWrap lineLength lineText |
| | | Text .length lineText <= lineLength = [lineText] |
If our line is longer than the maximum allowed line length, then we want to take as many characters as we can, and then wrap the rest of the text recursively. You might notice that the implementation here is similar to the groupsOf function you implemented earlier:
| | wordWrap :: Int -> Text . Text -> [ Text . Text ] |
| | wordWrap lineLength lineText |
| | | Text .length lineText <= lineLength = [lineText] |
| | | otherwise = |
| | let (wrapped, unwrapped) = Text .splitAt lineLength lineText |
| | in wrapped : wordWrap lineLength unwrapped |
One problem with this version of the code is that it will word wrap without respect to individual word boundaries. It would be convenient if we could preferentially break lines apart on word boundaries so that a word would only get separated if it were actually longer than the allowed width of the text. Let’s look at how we can update our wrapping function to better handle word boundaries.
The algorithm we’ll use is going to be a small modification to our existing hard-wrapping algorithm. Our base case will remain the same, and for lines that need to be wrapped we’ll still start by splitting the text at the maximum word boundary. After we’ve split our input in the current line of text, we’ll attempt to “soft wrap” the line. This helper function, which we’ll implement soon, will try to find the last word boundary in the text. If it can find one, it will return a tuple of the text before and after the word boundary. For example, if we are going to try to soft wrap the string "word wrapping is tricky" we would end up with the tuple ("word wrapping is", "tricky") . The wrapped part of the line will be the first element of our tuple. The remainder of the line will get prepended to the leftover text that we’ll wrap recursively.
The soft wrapping itself will recursively walk “backwards” through the input string. If the character we’re currently looking at is a space, then we’re at the last possible word boundary and we’ll split the string. If we get all the way to the beginning of the string and haven’t found a space, then the string must not have any natural word boundaries, and we’ll have to fall back to using the hard-wrapped input without any additional splitting.
Let’s look at the code, and then walk through an example:
| | wordWrap :: Int -> Text . Text -> [ Text . Text ] |
| | wordWrap lineLength lineText |
| | | Text .length lineText <= lineLength = [lineText] |
| | | otherwise = |
| | let |
| | (candidate, nextLines) = Text .splitAt lineLength lineText |
| | (firstLine, overflow) = softWrap candidate ( Text .length candidate - 1) |
| | in firstLine : wordWrap lineLength (overflow <> nextLines) |
| | where |
| | softWrap hardwrappedText textIndex |
| | | textIndex <= 0 = (hardwrappedText, Text .empty) |
| | | Text .index hardwrappedText textIndex == ' ' = |
| | let (wrappedLine, rest) = Text .splitAt textIndex hardwrappedText |
| | in (wrappedLine, Text .tail rest) |
| | | otherwise = softWrap hardwrappedText (textIndex - 1) |
To make it easier to understand this code, let’s step through what would happen when we call this function and try to wrap the string "word wrapping is tricky" to a length of six characters.
At first we’ll call our function with the two parameters:
| | wordWrap 6 "word wrapping is tricky" |
Our base case will fail to match, because our text is more than six characters long. That means we’ll begin by splitting our input into a candidate line of six characters, and everything else that still needs to be wrapped. We can see this in ghci :
| | λ Text .splitAt 6 "word wrapping is tricky" |
| | ( "word w" , "rapping is tricky" ) |
At this point, candidate is our candidate wrapped line, and it’s set to "word w" . The value of nextLines is "rapping is tricky" . The next thing we do is call softWrap with our candidate string and an index, which we’ll set to point at the end of the string.
| | softWrap "word w" 5 |
When we call softWrap our index is not less than, or equal to, zero, which would indicate that the string can’t be soft wrapped. Next we’ll check to see if the element at our current index is a space. Again, we can test this out in ghci :
| | λ Text .index "word w" 5 |
| | 'w' |
The index isn’t a space, so we’ll decrement the index and call softWrap recursively:
| | softWrap "word w" 4 |
This time, our index test will find a space:
| | λ Text .index "word w" 4 |
| | ' ' |
That means we’ve found a word break that we can soft wrap at. We’ll split the string here into our new line that is soft wrapped at a line break, and the rest of our text. If we test this out in ghci , we can see that the space we were just looking for is at the start of our leftover string:
| | λ Text .splitAt 4 "word w" |
| | ( "word" , " w" ) |
It would look bad to have all wrapped lines of text have a preceding space, so we’ll drop that space off the string before we return it. Now we have firstLine set to "word" and overflow set to "w" . Now it’s time for our recursive call. If we fill in the values for our variables we have:
| | "word" : wordWrap 6 ( "w" <> "rapping is tricky" ) |
Now we need to handle our recursive call to wrap the remainder of our text, "wrapping is tricky" . Once again, our initial string is too long and so we need to split it:
| | λ Text .splitAt 6 "wrapping is tricky" |
| | ( "wrappi" , "ng is tricky" ) |
In this case, the first word of our line of text is longer than the entire length of a line—it’s a good thing we accounted for that edge case! When we call softWrap we’ll step backwards through the entire string looking for a space, but of course we won’t find one this time, so we’ll hit our base case and return the hard wrapped version, "wrappi" . We’ll add that to our list of wrapped words and make another recursive call:
| | "word" : "wrappi" : wordWrap 6 ( "" <> "ng is tricky" ) |
The next two words that we handle will follow the same recursive process, and in the end we’ll end up with a wrapped string:
| | λ wordWrap 6 "word wrapping is tricky" |
| | [ "word" , "wrappi" , "ng is" , "tricky" ] |
Handling Terminal Dimensions
The last piece of our functional core is going to combine wordWrap and groupsOf into a single function that will paginate text. To do this we’ll need to take in both the width and height of the screen. To handle that, let’s create a new record called ScreenDimensions to hold the rows and columns of the screen:
| | data ScreenDimensions = ScreenDimensions |
| | { screenRows :: Int |
| | , screenColumns :: Int |
| | } deriving Show |
Now we’ll create a function called paginate that takes our screen dimensions and the text that we want to show and breaks it into a list of pages that will each fit on the screen comfortably. To do this, we’ll use Text.lines to turn our large bytestring into a list of individual lines of text. concatMap , which you’ve seen before, will let us map each of our lines of text into one or more lines of word-wrapped text, which we can then group into pages worth of lines. As a last step we’ll use Text.unlines to combine each of our pages back into a single bytestring for easy printing:
| | paginate :: ScreenDimensions -> Text . Text -> [ Text . Text ] |
| | paginate ( ScreenDimensions rows cols) text = |
| | let unwrappedLines = Text .lines text |
| | wrappedLines = concatMap (wordWrap cols) unwrappedLines |
| | pageLines = groupsOf rows wrappedLines |
| | in map Text .unlines pageLines |
Now that we’ve finished implementing the pure core of our feature, which will let us easily paginate some text, it’s time to work on the procedural shell of our application.
Calling External Applications
We’ve built a program that can fit some text to a screen given its dimensions, but we’ve got one major missing piece: how do we get the dimensions of the screen in the first place? One way that we could approach this is to simply ask the user to input the information when they open the file, but this would be an awful user experience. In most cases, there’s no easy way for a user to have that information available, so they’d need to tediously count rows and columns, or use a tool to give them the information. Another option would be to look for a library that gives us detailed terminal information. Low-level terminal libraries can be complicated though, and building something that works cross-platform can be a real challenge.
| System Dependent Code Ahead |
|---|
|
| Some aspects of this section are not entirely portable across all operating systems and configurations. When we call out to external applications or interact with a shell in this section we will necessarily have to make some assumptions about what kind of environment the application is running in, and what tools are available. All of the examples in this section have been tested on Linux and should work well in most typical Linux, MacOS, and BSD environments. If you are using Windows, most of these examples should work if you are using the Linux Subsystem for Windows. If you find yourself in an environment where some of these examples do not run as expected, you can experiment with the code to find something that works better for your system, or use a virtual machine so that you can experiment with the applications in a supported environment. |
There’s a tool named tput that’s available out of the box on most Unix-like systems that we can use to look up the size of the terminal in a platform independent way. Unfortunately for us though, tput is an executable program and not a library, so to call it we’ll need to run the application and parse its output. Dealing with calling external applications is something that comes up from time to time when building systems, and so in this section, we’ll look at how to create and manage the life cycle of external applications using the process [15] package.
At the core of the process package is a module, System.Process , that gives you the tools to spawn and interact with subprocesses. This module defines a few data types and includes several functions to help you work with external processes. Most of the functionality provided by the System.Process is concerned with giving you fine-grained control over processes, how they are spawned, and how they run. For our purposes, we don’t need fine-grained control and can make use of one of the higher level utility functions provided by the library, readProcess :
| | readProcess :: FilePath -> [ String ] -> String -> IO String |
The readProcess function let’s us run a program by providing it the name of a program or a path to the application we want to run, a list of arguments that it should receive, and any input that should be available to it over stdin . When readProcess is evaluated, the IO action will wait until the program has finished executing and will return all of the output that the program wrote to stdout as a String . Let’s look at an example in ghci :
| | λ import System.Process |
| | λ readProcess "cal" [ "01" , "1972" ] "" >>= putStrLn |
| | January 1972 |
| | Su Mo Tu We Th Fr Sa |
| | 1 |
| | 2 3 4 5 6 7 8 |
| | 9 10 11 12 13 14 15 |
| | 16 17 18 19 20 21 22 |
| | 23 24 25 26 27 28 29 |
| | 30 31 |
In this example, we’re calling the cal program to generate a calendar for January of the year 1972. You’ll notice that the first argument that we’re passing, "cal" , isn’t a full path. Most functions from the process library will use system-specific conventions for handling calls to programs. For example, on Unix-like systems, if you don’t provide a full path to a program, then it will look at the PATH environment variable to figure out what directories should be searched for applications. The second argument that we pass in is a list of arguments. The cal program can be optionally given a date and it will generate a calendar for the given month or year. Here we’re printing out a calendar of January, 1972, so we pass two arguments, "01" for January, and "1972" for the year 1972. Finally, running an external program is an IO action, and so we are binding the output of that IO action to the input of putStrLn using >>= .
For our pager application, we’ll need to use readProcess to call tput so that we can get the size of our terminal. We also want to make sure that we’re only going to call the command on systems where we expect it to be available. In our application we’ll concern ourselves with Darwin and Linux systems. For other systems, we’ll return a hard-coded default terminal size. The System.Info package exports a string named os that contains the name of the current OS. Putting all that together, here’s an example function to get the dimensions of a terminal:
| | import System.Process ( readProcess ) |
| | import qualified System.Info as SystemInfo |
| | getTerminalSize :: IO ScreenDimensions |
| | getTerminalSize = |
| | case SystemInfo .os of |
| | "darwin" -> tputScreenDimensions |
| | "linux" -> tputScreenDimensions |
| | _other -> pure $ ScreenDimensions 25 80 |
| | where |
| | tputScreenDimensions :: IO ScreenDimensions |
| | tputScreenDimensions = |
| | readProcess "tput" [ "lines" ] "" |
| | >>= \ lines -> |
| | readProcess "tput" [ "cols" ] "" |
| | >>= \ cols -> |
| | let lines' = read $ init lines |
| | cols' = read $ init cols |
| | in return $ ScreenDimensions lines' cols' |
It’s a little bit unwieldy! Later on in this chapter, in Improving Readability with Do Blocks , you’ll learn how to refactor this function so that it’s more readable. For now, we can still get a good idea of what’s happening here. We’re starting out looking at the current OS, and returning a default value if we’re not running on Darwin or Linux. Once the OS check is out of the way, we call Process.readProcess twice, once to get the number of lines in the terminal, and a second time to get the columns.
Like most processes, tput returns its output with a trailing newline. That’s handy on an interactive terminal because it makes sure that the cursor gets set back to the start of a line before your prompt is displayed, but when you’re calling a process programatically you need to strip it off. The init function is part of the standard library. It takes a list and returns all but the last element, which in this case is the newline character. The last thing we do is pass our string to read to convert the string into a number.
Our implementation is a bit fragile. The exercises section at the end of this chapter has some opportunities for how you can make this code more robust.
Getting User Input
The final challenge that we have with getting our pager working is being able to show a page based on user input. To do this, we’ll need to be able to read keypresses to control what the application does and then take an action based on the keypress. Let’s start by looking at how we can deal with representing the user input, and then we’ll look at how to get the input. Finally, we’ll bring it all together into a function that gets user input and acts on it accordingly.
We’ve decided that we want to control our application by using space to go to the next page and typing q to quit, so we’ll need to handle two separate keypresses. For the sake of simplicity, we’ll ignore any other keypresses.
Once we’ve displayed a page of text, our program won’t do anything until the user enters some text. Once we’ve gotten the text, if it’s input that we accept, we’ll use that input to decide if we should continue on to the next page, or cancel the application. We’ll encode those two choices into a new type called ContinueCancel :
| | data ContinueCancel = Continue | Cancel deriving ( Eq , Show ) |
Next we need to build a function that gets a ContinueCancel value inside of an IO action. It won’t have any input (aside from what the user gives it), so its type will be getContinue :: IO ContinueCancel .
Now that you understand how IO works, and have some experience reading files and writing things to the screen, implementing this function shouldn’t be too hard. We’ve worked with handles before to read and write to files. Working with the shell is essentially the same thing. Instead of getting a file handle by calling openFile we’ll just use the special handle stdin . The System.IO module gives you three handles when your application starts: stdin , stdout , and stderr . These all connect to the standard file descriptions for your application just like you’d expect.
Since we’re concerned with keypresses instead of entire lines or files of text, we’ll use the hGetChar function to get a single character at a time from stdin . These are both exported by the System.IO module in base . A naive implementation of our function might look something like this:
| | import System.IO |
| | |
| | getContinue :: IO ContinueCancel |
| | getContinue = |
| | hGetChar stdin |
| | >>= \ input -> |
| | case input of |
| | ' ' -> return Continue |
| | 'q' -> return Cancel |
In the next section, we’ll bring everything together and start using this function to display our paginated data. For now, we can temporarily modify our runHCat function to call getContinue so that we can see it in action:
| | runHCat :: IO () |
| | runHCat = |
| | putStrLn "do you want to Continue (space) or quit (q)" >> |
| | getContinue >>= |
| | \ cont -> |
| | case cont of |
| | Continue -> putStrLn "okay, continuing!" >> runHCat |
| | Cancel -> putStrLn "goodbye!" |
If you run the application right now you might notice that it doesn’t behave like you would expect. You can press space or the q key as many times as you want and nothing will happen. If you press enter, you might see several lines of output come across the screen all at once, and then the program will crash!
The spaces in this example are rendered as underscores to make it more obvious what’s happening:
| | user@host$ cabal run hcat |
| | do you want to Continue (space) or quit (q) |
| | ___ |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | hcat: src/ HCat .hs:(338,7)-(340,24): Non -exhaustive patterns in case |
The first problem we have is that the application isn’t reacting to our input until we press enter. This is due to the fact that most terminals by default are line buffered , which means that our program will get an entire line of text at a time, and the terminal won’t actually send us anything that the user has typed until they press enter. We can disable that by calling the hSetBuffering function to configure the type of buffering that we want to use. We want to get the keypresses as soon as the user enters them, so we’ll set it to NoBuffering . With that change in place our function will now be:
| | getContinue :: IO ContinueCancel |
| | getContinue = |
| | hSetBuffering stdin NoBuffering |
| | >> hGetChar stdin |
| | >>= \ input -> |
| | case input of |
| | ' ' -> return Continue |
| | 'q' -> return Cancel |
If we run our program again we’ll see slightly different behavior. Just like before, let’s press the spacebar three times, and then press enter:
| | user@host$ cabal run hcat |
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | |
| | hcat: src/HCat.hs:(338,7)-(340,24): Non-exhaustive patterns in case |
It’s looking a little better, but we still have a few problems. We display a message to the user each time we press the spacebar now, but we’re still crashing whenever we press enter. There’s also something wrong with the output. Let’s address the crash first.
The crash message is telling us that we have a non-exhaustive pattern in our case statement. The pattern that it’s referring to is at the end of our function, where we’re looking for the space or q characters. It turns out by not including anything to match the other characters that might get entered we’ve added a bug, and not ignored them like we intend. Let’s make a small change to our program. Instead of ignoring those characters, we’ll use a wildcard pattern to match any other letters, and in that case we’ll simply recursively call getContinue , which will again wait for another keypress:
| | getContinue :: IO ContinueCancel |
| | getContinue = |
| | hSetBuffering stdin NoBuffering |
| | >> hGetChar stdin |
| | >>= \ input -> |
| | case input of |
| | ' ' -> return Continue |
| | 'q' -> return Cancel |
| | _ -> getContinue |
Let’s run the program again:
| | do you want to Continue (space) or quit (q) |
| | okay, continuing! |
| | do you want to Continue (space) or quit (q) |
| | |
| | qgoodbye! |
If we press space we again see the message right away, and if we press enter our program no longer crashes! The output is still getting corrupted by our keypresses though. The extra space in front of our “okay, continuing!” message might be easy to overlook, but the “q” in front of our “goodbye!” message is harder to ignore. The problem that we have is terminal echoing . By default, a terminal will output any characters that the user types to the screen. In the normal case that’s what we want, but for a tool like hcat where we are building a more interactive UI, we want to suppress that. We can change this behavior by disabling terminal echoing, so the users keypresses don’t show up on the screen. Just like with buffering, we can disable echo on stdin by calling hSetEcho :
| | getContinue :: IO ContinueCancel |
| | getContinue = |
| | hSetBuffering stdin NoBuffering |
| | >> hSetEcho stdin False |
| | >> hGetChar stdin |
| | >>= \ input -> |
| | case input of |
| | ' ' -> return Continue |
| | 'q' -> return Cancel |
| | _ -> getContinue |
If you run the program now you’ll see that everything should behave as expected. We can get user input without buffering, hide the keypresses so that they don’t corrupt the output, and silently ignore any keypresses that we’re not expecting. Now that we can control our pager, let’s move on to connecting all of the pieces of our application togther.
Paging Our File
Now that we’ve gotten all of the individual components of our functional core and procedural shell built, we can finally put everything together and paginate a file for our user! In this section we’ll add one more function, and then make some updates to runHCat to bring everything together.
Let’s start with our new function. We haven’t yet written a function to actually print a page of text to the screen. We’ll create a new function called showPages to show all of the pages of our document. Let’s take a look at the code first, and then we can walk through it:
| | showPages :: [ Text . Text ] -> IO () |
| | showPages [] = return () |
| | showPages (page:pages) = |
| | TextIO .putStrLn page |
| | >> getContinue |
| | >>= \ input -> |
| | case input of |
| | Continue -> showPages pages |
| | Cancel -> return () |
We’re using pattern matching here to detect when we’ve shown all of our pages. For cases where we still have a page, our algorithm is pretty simple: we print out the page, and then we wait for the user to make a keypress. If they want to continue, we show the next page, and otherwise we just finish our IO action.
There’s one small quirk of our implementation that might be inconvenient: when we view a short file, we don’t clear the screen. That means it might be hard for a user to tell how much of the text they are looking at is from the current file, and how much is just left from previous output to their terminal.
We can address this by clearing the screen before we print any page of text. This can be done using ANSI terminal escape sequences, which are supported in Linux, BSD, MacOS, and recent versions of Windows. You can look up the details of the ANSI escape sequences online, or copy the example to get an IO action that will print out the correct escape sequence to clear the screen and reset the cursor position to the top-left of the console:
| | clearScreen :: IO () |
| | clearScreen = |
| | BS .putStr " \^[ [1J \^[ [1;1H" |
There are a couple of things that might get your attention when you look at this code. First, you’ll notice we’re using a ByteString rather than a Text value. We could use Text here, since both ByteString and Text support the types of values that we want to use. In this case though, ByteString is semantically a better choice. Even though we’re typing in a string, our escape sequence is logically a raw byte sequence. We wouldn’t want it to be interpreted as Unicode if we were to try to do something with the string later on.
| OverloadedStrings |
|---|
|
| The OverloadedStrings extension has been available since GHC 6.8.1. This extension isn’t enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is a popular extension, and many projects enable it by default in their cabal files so that it can be used across an entire codebase. This extension does introduce some changes that can make errors harder to understand and, since it changes the meaning of string literals, some existing projects might not compile when this extension enabled. |
Speaking of typing in a byte sequence, you might also notice that we’ve typed in a literal string value here, but the compiler is accepting it as a ByteString value rather than a normal String . If you copy this code into your example as-is, you will find that you’ll get an error. Being able to type literal values for string types like Text and ByteString is extremely convenient, and so we have a language extension, OverloadedStrings , which allows us to do just that. Let’s add it to the top of our file:
| | {-# LANGUAGE OverloadedStrings #-} |
Now that we have a way to clear the screen, we can update showPages :
| | showPages :: [ Text . Text ] -> IO () |
| | showPages [] = return () |
| | showPages (page:pages) = |
| | clearScreen |
| | >> TextIO .putStr page |
| | >> getContinue |
| | >>= \ input -> |
| | case input of |
| | Continue -> showPages pages |
| | Cancel -> return () |
Updating our main runHCat function is likewise pretty straightforward. We just need to get the contents of our file, then paginate it before passing it to showPages :
| | runHCat :: IO () |
| | runHCat = |
| | handleArgs |
| | >>= eitherToErr |
| | >>= flip openFile ReadMode |
| | >>= TextIO .hGetContents |
| | >>= \ contents -> |
| | getTerminalSize >>= \ termSize -> |
| | let pages = paginate termSize contents |
| | in showPages pages |
If you build your application and run it now you’ll see how you can combine a procedural shell with a functional core to combine pure functions, like our word wrap and pagination function, with IO actions like getting user input, handling errors, or calling external processes.
Take a moment to spend some time running the program and watching it work. In the next section, we’ll build on the program to add some new capabilities, and then we’ll look at ways that we can refactor the code to make it easier to work with.