Xmonad/Mutable state in contrib modules or xmonad.hs

From HaskellWiki
< Xmonad
Revision as of 19:57, 30 January 2011 by DanielSchoepe (talk | contribs) (Data.IORef: Note about persistency)

Jump to: navigation, search

This page describes how to keep track of mutable state in a module in xmonad-contrib or in the configuration.

General options


Layouts can keep track of their state placing the information in the data type that is an instance of LayoutClass. The various methods of this typeclass allow one to update this information by supplying a new value of this type as a return value.

Note that this sensible for per-workspace state.


A more general way is to store data using Data.IORef. To create an IORef, one uses newIORef; the returned value can then be passed to functions for reading from or writing to it.

Here is an example for a keybinding that keeps track of how many times it has been pressed:

import Data.IORef
updatingBinding :: IORef Integer -> X ()
updatingBinding ref = do
  val <- io $ readIORef ref
  io $ writeIORef ref (val+1)
  spawn $ "xmessage I have been pressed " ++ show val ++ " times before!"

To use this, it needs to be passed an IORef as a parameter:

import Data.IORef
import XMonad.Util.EZConfig
main = do
  ref <- newIORef 0 -- this is the initival value
  xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding ref)]

Note that using IORefs is not persistent across xmonad restarts.

Implicit Parameters

This extension is useful for passing in the iorefs. You generally need these two extensions together, if you like to leave out the type signatures (which are as much work as explicitly passing the parameters):

{-# LANGUAGE ImplicitParams, NoMonomorphismRestriction #-}

main = do
  ref <- newIORef 0
  let ?ref = ref -- all references to ?ref later on will be this one
  xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding)]

-- updatingBinding :: (?ref :: IORef Integer) => X () -- this is the actual type
updatingBinding = do
  val <- io $ readIORef ?ref
  io $ writeIORef ?ref (val+1)
  spawn $ "xmessage I have been pressed " ++ show val ++ " times before!"


This is even less desirable alternative, but it is one of the more acceptable uses of this unsafe function.

Basically, you create a top-level IORef which is forced to be a single copy:

{-# NOINLINE ref #-}
ref = unsafePerformIO (newIORef 0)

Previous versions of xmonad had this used in some contrib modules such as XMonad.Hooks.UrgencyHook source here.


Refer to haddock documentation.

Only available in darcs


This module allows you to store data in xmonad's internal state eliminating the need to explicitly pass around the IORef value seen in the previous example.

For information on how to use it, refer to the module's documentation.