我的xmonad配置

缺点

  • 依赖的模块较多,升级 ghc 或被 xmonad/xmonad-contrib 依赖的包后需要按照拓扑序更新整个被 xmonad 依赖的树。 如果平时不大升级的就不用在意这一点。
  • 没有 systray 等其他 desktop environment 集成的组件,这方面 tiling window manager 世界中的 Awesome 可谓是佼佼者, 其他 wm 都需要手动配置很多组件,Xmonad 也不例外。

优点

  • Xmonad 用 Haskell 配置,因为这一点注定了当配置复杂到一定程度后,会远远胜过 那些自定义配置语言的 wm。
  • 得到 monad transformer 精髓的 layout transformer 使得复合 layout 变得非常容易, 可以轻易定制出在其他 wm 中不可能实现的 layout。

xmonad-contrib 模块推荐

  • XMonad.Util.EZConfig。支持 key sequence。一个 Meta 键是不够用的,我们需要 Emacs 风格的 key sequence。 在很多 wm 里这个是做不到的,而 Xmonad 有 XMonad.Util.EZConfig 可以实现这个。
  • XMonad.Util.Scratchpad。方便控制浮动的终端应用程序窗口的出现,比如 alsa-mixerghcitask 等。 配置一个快捷键,作用是 toggle 某个窗口是否在当前工作区出现。 Scratchpad 上图是各个REPL的scratchpad。
  • XMonad.Actions.Navigation2D。符合直觉的在窗口间切换焦点的方式,也适用于浮动窗口。比如配置 M-h 为把焦点移动到左边的窗口。 这个模块实现了两种算法实现了该功能。 可以参看我的 http://maskray.me/blog/2012-01-11-tiling-window-manager-application-and-design,描述了 该算法。 Navigation2D 光标原来在 before 这个 urxvtc 里,选择把焦点移动到上方的窗口后,焦点换到了 after 这个 urxvtc
  • XMonad.Actions.MouseGestures。鼠标手势。
  • XMonad.Actions.GridSelect。显示一个2D的格子,每个格子绑定到一个需要执行的命令,用hjkl或鼠标选择。 GridSelect
  • XMonad.Actions.Search。弹出一个文本框,输出字符串,回车,搜索! Prompt 我用 M-/ 后接一个字母指示使用的搜索引擎,比如 g(google)h(hoogle) 等。 按 M-S-/ 后,则是同时输出搜索引擎的搜索文本,比如 g text,表示用 google 搜索 text。

我的配置

github上的配置文件

其他

sawfish 有个很方便的功能 jump-or-exec,就是输入一个快捷键,如果对应的程序未运行则运行,否则跳转到对应的窗口。 xmonad-contrib 中的 XMonad.Actions.TopicSpaceTopic 划分不同工作区,不同 Topic 的工作目录不同。它提供了这样一个功能:当某个工作区没有窗口时则执行指定命令。通过把不同类型程序放到不同工作区,就能模拟 jump-or-exec。(XMonad.Actions.WindowGo 中也有直接对应 jump-or-execrunOrRaiseNext,但 Topic 的管理方式感觉更加科学。)我用 C-;asdfghjkl; 中的一个来切换不同工作区。带上 shift 则是把当前窗口移动到该工作区。

XMonad.Hooks.FadeInactive 中的 fadeInactiveLogHook 用来半透明没有获得焦点的窗口。

不同工作区我使用了不同的图标,例如 firefox 的图标代表工作区 web,当前工作区设置显示为默认图标,其他工作区显示为灰图表,含有 urgency 信息的窗口采用橙底的图标。点击图标会调用 wmctrl 转到相应工作区。这些图标可以用下面的脚本生成,把 firefox.png xterm.xpm 之类的文件放在 ~/.xmonad/icons/original/,下面脚本会生成对应的三种类型的 .xpm 图片。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
##!/bin/sh
DIR=~/.xmonad/icons
ORIG=$DIR/original
DEFAULT=$DIR/default
GRAY=$DIR/gray
HI=$DIR/highlight
mkdir $DEFAULT $GRAY $HI
rm $DEFAULT/*.xpm $GRAY/*.xpm $HI/*.xpm
for i in $ORIG/*; do
f=${i##*/}
f=${f%.*}.xpm
convert -resize 24x24 $i $DEFAULT/$f
convert -resize 24x24 -colorspace Gray $i $GRAY/$f
convert -resize 24x24 -background orange -flatten $i $HI/$f
done

我通过 XMonad.Hooks.DynamicLog 来把 xmonad 的窗口管理信息输出给 dzen2,如窗口标题,工作区布局等。

我用快捷键 C-' eC-' o 等来运行常用的程序如 eix-syncofflineimap,因为觉得这些程序不值得单独占用工作区,就放到了 NamedScratchpad 中,需要时按快捷键呼出(显示为浮动窗口)。

M-<L>M-S-<L> 等是用来移动、放大缩小当前窗口的。C-; <L> 是把当前窗口往左移动直到碰到其他窗口。 M-S-i 调用 xcalib -i -a 使显示器反色,M-S-k 调用 xkill 杀窗口。 M-y 跳转到带有 urgency 信息的窗口,M-b 显示/隐藏 dzen2trayer

XMonad.Actions.Search 来实现搜索功能,M-/ 加其他键来表示各种搜索方式:GoogleWikipedia 等。 xmonad 会弹出一个窗口要求输入查询字符串,然后调用 firefox 来查询。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
{-# LANGUAGE
TypeSynonymInstances,
MultiParamTypeClasses,
DeriveDataTypeable
#-}

import Control.Monad
import Codec.Binary.UTF8.String (encodeString)
import Data.Char
import Data.List
import qualified Data.Map as M
import Data.Maybe (isNothing, isJust, catMaybes, fromMaybe)
import Data.Function
import Data.Monoid
import System.Exit
import System.IO
import System.Process
import System.Posix.Process (executeFile)
import System.Posix.Types (ProcessID)
import Text.Printf
import Text.Regex

import XMonad hiding ((|||))
import qualified XMonad.StackSet as W
import XMonad.Util.ExtensibleState as XS
import XMonad.Util.EZConfig
import XMonad.Util.Loggers
import XMonad.Util.NamedWindows (getName)
import XMonad.Util.NamedScratchpad
import XMonad.Util.Paste
import XMonad.Util.Run
import qualified XMonad.Util.Themes as Theme
import XMonad.Util.WorkspaceCompare

import XMonad.Prompt
import XMonad.Prompt.Input
import XMonad.Prompt.Man
import XMonad.Prompt.RunOrRaise
import XMonad.Prompt.Shell
import XMonad.Prompt.Window
import XMonad.Prompt.Workspace

import qualified XMonad.Actions.FlexibleManipulate as Flex
import XMonad.Actions.Commands
import XMonad.Actions.CycleRecentWS
import XMonad.Actions.CycleWS
import XMonad.Actions.DynamicWorkspaces
import XMonad.Actions.FloatKeys
import XMonad.Actions.FloatSnap
import XMonad.Actions.GridSelect
import XMonad.Actions.Navigation2D
import qualified XMonad.Actions.Search as S
import XMonad.Actions.Submap
import XMonad.Actions.SpawnOn
import XMonad.Actions.TopicSpace
import XMonad.Actions.UpdatePointer
import XMonad.Actions.Warp
import XMonad.Actions.WindowBringer
import XMonad.Actions.WindowGo
import XMonad.Actions.WindowMenu
import XMonad.Actions.WithAll (sinkAll, killAll)

import XMonad.Hooks.DynamicLog
import XMonad.Hooks.FadeInactive
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.Place
import XMonad.Hooks.UrgencyHook

import XMonad.Layout.Mosaic
import XMonad.Layout.AutoMaster
import XMonad.Layout.DragPane
import qualified XMonad.Layout.HintedGrid as HintedGrid
import XMonad.Layout.Grid
import XMonad.Layout.LayoutCombinators
import XMonad.Layout.Master
import XMonad.Layout.Maximize
import XMonad.Layout.MultiToggle
import XMonad.Layout.MultiToggle.Instances
import XMonad.Layout.Named
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Reflect
import XMonad.Layout.Renamed
import XMonad.Layout.ResizableTile
import XMonad.Layout.Tabbed
import XMonad.Layout.WindowNavigation
import XMonad.Layout.WorkspaceDir
import XMonad.Layout.WindowSwitcherDecoration
import XMonad.Layout.DraggingVisualizer
import qualified XMonad.Layout.Magnifier as Mag

{-
- TABBED
-}

myTabTheme = (Theme.theme Theme.kavonChristmasTheme)
{ fontName = "DejaVu Sans Mono:pixelsize=16"
, decoHeight = 20
}

data TABBED = TABBED deriving (Read, Show, Eq, Typeable)
instance Transformer TABBED Window where
transform _ x k = k (renamed [Replace "TABBED"] (tabbedAlways shrinkText myTabTheme)) (const x)

{-
- Navigation2D
-}

myNavigation2DConfig = defaultNavigation2DConfig { layoutNavigation = [("Full", centerNavigation)]
, unmappedWindowRect = [("Full", singleWindowRect)]
}

myLayout = avoidStruts $
configurableNavigation (navigateColor "#00aa00") $
mkToggle1 TABBED $
mkToggle1 NBFULL $
mkToggle1 REFLECTX $
mkToggle1 REFLECTY $
mkToggle1 MIRROR $
mkToggle1 NOBORDERS $
smartBorders $
--onWorkspaces ["web","irc"] Full $
Full ||| dragPane Horizontal 0.1 0.3 ||| ResizableTall 1 (3/100) (1/2) [] ||| mosaic 1.5 [7,5,2] ||| autoMaster 1 (1/20) (Mag.magnifier Grid) ||| HintedGrid.GridRatio (4/3) False

doSPFloat = customFloating $ W.RationalRect (1/6) (1/6) (4/6) (4/6)
myManageHook = composeAll $
[ className =? c --> doShift "web" | c <- ["Firefox", "Google-chrome"] ] ++
[ className =? c --> doShift "code" | c <- ["Gvim"] ] ++
[ className =? c --> doShift "doc" | c <- ["Okular", "MuPDF", "llpp", "Recoll", "Evince", "Zathura"] ] ++
[ title =? "newsbeuter" --> doShift "news"] ++
[ title =? "mutt" --> doShift "mail"] ++
[ className =? c --> doShift "dict" | c <- ["Goldendict", "Stardict"] ] ++
[ className =? c --> viewShift "media" | c <- ["feh", "Display"] ] ++
[ prefixTitle "emacs" --> doShift "emacs" ] ++
[ className =? c --> doShift "net" | c <- ["Wpa_gui"] ] ++
[ prefixTitle "libreoffice" <||> prefixTitle "LibreOffice" --> doShift "office" ] ++
[ className =? "Do" --> doIgnore ] ++
[ myFloats --> doSPFloat ] ++
[ manageDocks , namedScratchpadManageHook scratchpads ] ++
[ className =? c --> ask >>= \w -> liftX (hide w) >> idHook | c <- ["XClipboard"] ]
where
prefixTitle prefix = fmap (prefix `isPrefixOf`) title
viewShift = doF . liftM2 (.) W.greedyView W.shift
myFloats = foldr1 (<||>)
[ className =? "Firefox" <&&> fmap (/="Navigator") appName
, className =? "Nautilus" <&&> fmap (not . isSuffixOf " - File Browser") title
, stringProperty "WM_WINDOW_ROLE" =? "pop-up"
, fmap (isPrefixOf "sun-") appName
, fmap (isPrefixOf "Gnuplot") title
, flip fmap className $ flip elem
[ "XClock"
, "Xmessage"
, "Floating"
]
]

myDynamicLog h = dynamicLogWithPP $ defaultPP
{ ppCurrent = ap clickable (wrap "^i(/home/ray/.xmonad/icons/default/" ")" . fromMaybe "application-default-icon.xpm" . flip M.lookup myIcons)
, ppHidden = ap clickable (wrap "^i(/home/ray/.xmonad/icons/gray/" ")" . fromMaybe "application-default-icon.xpm" . flip M.lookup myIcons)
, ppUrgent = ap clickable (wrap "^i(/home/ray/.xmonad/icons/highlight/" ")" . fromMaybe "application-default-icon.xpm" . flip M.lookup myIcons)
, ppSep = dzenColor "#0033FF" "" " | "
, ppWsSep = ""
, ppTitle = dzenColor "green" "" . shorten 45
, ppLayout = flip (subRegex (mkRegex "ReflectX")) "[|]" .
flip (subRegex (mkRegex "ReflectY")) "[-]" .
flip (subRegex (mkRegex "Mirror")) "[+]"
, ppOrder = \(ws:l:t:exs) -> [t,l,ws]++exs
, ppSort = fmap (namedScratchpadFilterOutWorkspace.) (ppSort byorgeyPP)
, ppExtras = [ dzenColorL "violet" "" $ date "%R %a %y-%m-%d"
, dzenColorL "orange" "" battery
]
, ppOutput = hPutStrLn h
}
where
clickable w = wrap ("^ca(1,wmctrl -s `wmctrl -d | grep "++w++" | cut -d' ' -f1`)") "^ca()"

{-
- Bindings
-}

myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
[ ((modm, button1), (\w -> focus w >> Flex.mouseWindow Flex.position w))
, ((modm, button2), (\w -> focus w >> Flex.mouseWindow Flex.linear w))
, ((modm, button3), (\w -> focus w >> Flex.mouseWindow Flex.resize w))
]

myKeys =
[ ("M-" ++ m ++ [k], f i)
| (i, k) <- zip myTopicNames "1234567890-="
, (f, m) <- [ (switchTopic myTopicConfig, "")
, (windows . liftM2 (.) W.view W.shift, "S-")
]
]
++
[ ("C-; " ++ m ++ [k], f i)
| (i, k) <- zip myTopicNames "asdfghjkl;'\""
, (f, m) <- [ (switchTopic myTopicConfig, "")
, (windows . liftM2 (.) W.view W.shift, "S-")
]
]
++
[("M-" ++ m ++ k, screenWorkspace sc >>= flip whenJust (windows . f))
| (k, sc) <- zip ["w", "e", "r"] [0..]
, (f, m) <- [(W.view, ""), (liftM2 (.) W.view W.shift, "S-")]
]
++
[ ("M-S-q", io exitFailure)
, ("M-S-c", kill)
, ("M-q", spawn "ghc -e ':m +XMonad Control.Monad System.Exit' -e 'flip unless exitFailure =<< recompile False' && xmonad --restart")

, ("<Print>", spawn "import /tmp/screen.jpg")
, ("C-<Print>", spawn "import -window root /tmp/screen.jpg")
, ("M-<Return>", spawn "urxvtc" >> sendMessage (JumpToLayout "ResizableTall"))
, ("M-g", spawnSelected defaultGSConfig ["urxvtd -q -f -o", "xterm", "google-chrome", "firefox-bin", "emacs --daemon", "desmume", "VisualBoyAdvance "])
, ("M-S-i", spawn "xcalib -i -a")
, ("M-S-l", spawn "xscreensaver-command -lock")
, ("M-S-k", spawn "xkill")
, ("<XF86AudioNext>", spawn "mpc_seek forward")
, ("<XF86AudioPrev>", spawn "mpc_seek backward")
, ("<XF86AudioRaiseVolume>", spawn "change_volume up")
, ("<XF86AudioLowerVolume>", spawn "change_volume down")
, ("<XF86AudioMute>", spawn "amixer set Master mute")
, ("<XF86AudioPlay>", spawn "mpc toggle")
, ("<XF86Eject>", spawn "eject")
, ("M-S-a", sendMessage Taller)
, ("M-S-z", sendMessage Wider)
, ("M-f", placeFocused $ withGaps (22, 0, 0, 0) $ smart (0.5,0.5))

-- window management
, ("M-<Tab>", cycleRecentWS [xK_Super_L] xK_Tab xK_Tab)
, ("M-n", doTo Next EmptyWS getSortByIndex (windows . liftM2 (.) W.view W.shift))
, ("M-<Space>", sendMessage NextLayout)
, ("M-i", sendMessage Shrink)
, ("M-o", sendMessage Expand)
, ("M-t", withFocused $ windows . W.sink)
, ("M-,", sendMessage (IncMasterN 1))
, ("M-.", sendMessage (IncMasterN (-1)))
, ("M-b", windowPromptBring myXPConfig)
, ("M-S-b", banishScreen LowerRight)
, ("M-s", sinkAll)
, ("M-y", focusUrgent)
, ("M-;", switchLayer)
, ("M-h", windowGo L True)
, ("M-j", windowGo D True)
, ("M-k", windowGo U True)
, ("M-l", windowGo R True)
, ("M-S-<L>", withFocused (keysResizeWindow (-30,0) (0,0))) --shrink float at right
, ("M-S-<R>", withFocused (keysResizeWindow (30,0) (0,0))) --expand float at right
, ("M-S-<D>", withFocused (keysResizeWindow (0,30) (0,0))) --expand float at bottom
, ("M-S-<U>", withFocused (keysResizeWindow (0,-30) (0,0))) --shrink float at bottom
, ("M-C-<L>", withFocused (keysResizeWindow (30,0) (1,0))) --expand float at left
, ("M-C-<R>", withFocused (keysResizeWindow (-30,0) (1,0))) --shrink float at left
, ("M-C-<U>", withFocused (keysResizeWindow (0,30) (0,1))) --expand float at top
, ("M-C-<D>", withFocused (keysResizeWindow (0,-30) (0,1))) --shrink float at top
, ("M-<L>", withFocused (keysMoveWindow (-30,0)))
, ("M-<R>", withFocused (keysMoveWindow (30,0)))
, ("M-<U>", withFocused (keysMoveWindow (0,-30)))
, ("M-<D>", withFocused (keysMoveWindow (0,30)))
, ("C-; <L>", withFocused $ snapMove L Nothing)
, ("C-; <R>", withFocused $ snapMove R Nothing)
, ("C-; <U>", withFocused $ snapMove U Nothing)
, ("C-; <D>", withFocused $ snapMove D Nothing)

-- dynamic workspace
, ("M-C-n", addWorkspacePrompt myXPConfig)
, ("M-C-r", removeWorkspace)
, ("M-C-S-r", killAll >> removeWorkspace)

-- Volume
, ("C-; 9", spawn "change_volume down")
, ("C-; 0", spawn "change_volume up")
, ("C-; m", spawn "change_volume toggle")

-- preferred cui programs
, ("C-; C-;", pasteChar controlMask ';')
, ("C-' C-'", pasteChar controlMask '\'')
, ("C-' g", namedScratchpadAction scratchpads "ghci")
, ("C-' l", namedScratchpadAction scratchpads "lua")

, ("C-' q", namedScratchpadAction scratchpads "swipl")
, ("C-' o", namedScratchpadAction scratchpads "ocaml")
, ("C-' e", namedScratchpadAction scratchpads "erl")
, ("C-' p", namedScratchpadAction scratchpads "ipython")
, ("C-' r", namedScratchpadAction scratchpads "pry")
, ("C-' s", namedScratchpadAction scratchpads "gst")
, ("C-' j", namedScratchpadAction scratchpads "node")
, ("C-' f", namedScratchpadAction scratchpads "coffee")
, ("C-' a", namedScratchpadAction scratchpads "alsamixer")
, ("C-' c", namedScratchpadAction scratchpads "capture")
, ("C-' m", namedScratchpadAction scratchpads "ncmpcpp")
, ("C-' h", namedScratchpadAction scratchpads "htop")

, ("M-C-<Space>", sendMessage $ Toggle NBFULL)
, ("M-C-t", sendMessage $ Toggle TABBED)
, ("M-C-x", sendMessage $ Toggle REFLECTX)
, ("M-C-y", sendMessage $ Toggle REFLECTY)
, ("M-C-m", sendMessage $ Toggle MIRROR)
, ("M-C-b", sendMessage $ Toggle NOBORDERS)

-- prompts
, ("M-'", workspacePrompt myXPConfig (switchTopic myTopicConfig) )
, ("M-p c", mainCommandPrompt myXPConfig)
, ("M-p d", changeDir myXPConfig)
, ("M-p f", fadePrompt myXPConfig)
--, ("M-p m", manPrompt myXPConfig)
, ("M-p p", runOrRaisePrompt myXPConfig)
, ("M-p e", launchApp myXPConfig "evince" ["pdf","ps"])
, ("M-p F", launchApp myXPConfig "feh" ["png","jpg","gif"])
, ("M-p l", launchApp myXPConfig "llpp" ["pdf","ps"])
, ("M-p m", launchApp myXPConfig "mupdf" ["pdf","ps"])
, ("M-p z", launchApp myXPConfig "zathura" ["pdf","ps"])
, ("M-p M-p", runOrRaisePrompt myXPConfig)
] ++
searchBindings

scratchpads =
map f ["erl", "ghci", "gst", "node", "swipl", "coffee", "ipython", "lua", "pry", "alsamixer", "htop", "xosview", "ncmpcpp"] ++
[ NS "ocaml" "urxvtc -T ocaml -e rlwrap ocaml" (title =? "ocaml") doSPFloat
, NS "agenda" "org-agenda" (title =? "Agenda Frame") orgFloat
, NS "capture" "org-capture" (title =? "Capture Frame") orgFloat
, NS "eix-sync" "urxvtc -T eix-sync -e sh -c \"sudo eix-sync; read\"" (title =? "eix-sync") doTopFloat
, NS "getmail" "urxvtc -T getmail -e getmail -r rc0 -r rc1" (title =? "getmail") doTopRightFloat
]
where
urxvt prog = ("urxvtc -T "++) . ((++) . head $ words prog) . (" -e "++) . (prog++) $ ""
f s = NS s (urxvt s) (title =? s) doSPFloat
doTopFloat = customFloating $ W.RationalRect (1/3) 0 (1/3) (1/3)
doTopLeftFloat = customFloating $ W.RationalRect 0 0 (1/3) (1/3)
doTopRightFloat = customFloating $ W.RationalRect (2/3) 0 (1/3) (1/3)
doBottomLeftFloat = customFloating $ W.RationalRect 0 (2/3) (1/3) (1/3)
doBottomRightFloat = customFloating $ W.RationalRect (2/3) (2/3) (1/3) (1/3)
doLeftFloat = customFloating $ W.RationalRect 0 0 (1/3) 1
orgFloat = customFloating $ W.RationalRect (1/2) (1/2) (1/2) (1/2)

myConfig dzen = ewmh $ withNavigation2DConfig myNavigation2DConfig $ withUrgencyHook NoUrgencyHook $ defaultConfig
--myConfig dzen = ewmh $ withUrgencyHook NoUrgencyHook $ defaultConfig
{ terminal = "urxvtc"
, focusFollowsMouse = False
, borderWidth = 1
, modMask = mod4Mask
, workspaces = myTopicNames
, normalBorderColor = "#dbdbdb"
, focusedBorderColor = "#3939ff"
, mouseBindings = myMouseBindings
, layoutHook = myLayout
, manageHook = myManageHook
, logHook = fadeOutLogHook myFadeHook >> myDynamicLog dzen
, startupHook = checkKeymap (myConfig dzen) myKeys >> spawn "~/bin/start-tiling"
} `additionalKeysP` myKeys

defaultFade = 8/10
data FadeState = FadeState Rational (M.Map Window Rational) deriving (Typeable,Read,Show)
instance ExtensionClass FadeState where
initialValue = FadeState defaultFade M.empty
extensionType = PersistentExtension

myFadeHook :: Query Rational
myFadeHook = do
w <- ask
FadeState fadeUnfocused fadeSet <- liftX XS.get
case M.lookup w fadeSet of
Just v -> return v
Nothing -> do
b <- isUnfocused
return $ if b then fadeUnfocused else 1

myPromptKeymap = M.union defaultXPKeymap $ M.fromList
[
((controlMask, xK_g), quit)
, ((controlMask, xK_m), setSuccess True >> setDone True)
, ((controlMask, xK_j), setSuccess True >> setDone True)
, ((controlMask, xK_h), deleteString Prev)
, ((controlMask, xK_f), moveCursor Next)
, ((controlMask, xK_b), moveCursor Prev)
, ((controlMask, xK_p), moveHistory W.focusDown')
, ((controlMask, xK_n), moveHistory W.focusUp')
, ((mod1Mask, xK_p), moveHistory W.focusDown')
, ((mod1Mask, xK_n), moveHistory W.focusUp')
, ((mod1Mask, xK_b), moveWord Prev)
, ((mod1Mask, xK_f), moveWord Next)
]

myXPConfig = defaultXPConfig
{ font = "xft:DejaVu Sans Mono:pixelsize=16"
, bgColor = "#0c1021"
, fgColor = "#f8f8f8"
, fgHLight = "#f8f8f8"
, bgHLight = "steelblue3"
, borderColor = "DarkOrange"
, promptBorderWidth = 1
, position = Top
, historyFilter = deleteConsecutive
, promptKeymap = myPromptKeymap
}

-- | Like 'spawn', but uses bash and returns the 'ProcessID' of the launched application
spawnBash :: MonadIO m => String -> m ProcessID
spawnBash x = xfork $ executeFile "/bin/bash" False ["-c", encodeString x] Nothing

main = do
checkTopicConfig myTopicNames myTopicConfig
d <- openDisplay ""
let w = fromIntegral $ displayWidth d 0 :: Int
h = fromIntegral $ displayHeight d 0 :: Int
let barWidth = h `div` 13
let barHeight = h `div` 35
let fontSize = h `div` 54
dzen <- spawnPipe $ "killall dzen2; dzen2 -x " ++ (show $ barWidth*5) ++ " -h " ++ show barHeight ++ " -ta right -fg '#a8a3f7' -fn 'WenQuanYi Micro Hei-" ++ show fontSize ++ "'"
-- remind <http://www.roaringpenguin.com/products/remind>
dzenRem <- spawnBash $ "rem | tail -n +3 | grep . | { read a; while read t; do b[${#b[@]}]=$t; echo $t; done; { echo $a; for a in \"${b[@]}\"; do echo $a; done; } | dzen2 -p -x " ++ show barWidth ++ " -w " ++ (show $ barWidth*4) ++ " -h " ++ show barHeight ++ " -ta l -fg '#a8a3f7' -fn 'WenQuanYi Micro Hei-" ++ show fontSize ++ "' -l ${#b[@]}; }"
spawn $ "killall trayer; trayer --align left --edge top --expand false --width " ++ show barWidth ++ " --transparent true --tint 0x000000 --widthtype pixel --SetPartialStrut true --SetDockType true --height " ++ show barHeight
xmonad $ myConfig dzen

{-
- SearchMap
-}

searchBindings = [ ("M-S-/", S.promptSearch myXPConfig multi) ] ++
[ ("M-/ " ++ name, S.promptSearch myXPConfig e) | e@(S.SearchEngine name _) <- engines, length name == 1 ]
where
promptSearch (S.SearchEngine _ site)
= inputPrompt myXPConfig "Search" ?+ \s ->
(S.search "google-chrome" site s >> viewWeb)
viewWeb = windows (W.view "web")

mk = S.searchEngine
engines = [ mk "h" "http://www.haskell.org/hoogle/?q="
, mk "g" "http://www.google.com/search?num=100&q="
, mk "t" "http://developer.gnome.org/search?q="
, mk "w" "http://en.wikipedia.org/wiki/Special:Search?go=Go&search="
, mk "d" "http://duckduckgo.com/?q="
, mk "m" "https://developer.mozilla.org/en-US/search?q="
, mk "e" "http://erldocs.com/R15B/mnesia/mnesia.html?search="
, mk "r" "http://www.ruby-doc.org/search.html?sa=Search&q="
, mk "p" "http://docs.python.org/search.html?check_keywords=yes&area=default&q="
, mk "s" "https://scholar.google.de/scholar?q="
, mk "i" "https://ixquick.com/do/search?q="
, mk "gt" "https://bugs.gentoo.org/buglist.cgi?quicksearch="
, mk "dict" "http://www.dict.cc/?s="
, mk "imdb" "http://www.imdb.com/find?s=all&q="
, mk "def" "http://www.google.com/search?q=define:"
, mk "img" "http://images.google.com/images?q="
, mk "gh" "https://github.com/search?q="
, mk "bb" "https://bitbucket.org/repo/all?name="
, mk "alpha" "http://www.wolframalpha.com/input/i="
, mk "ud" "http://www.urbandictionary.com/define.php?term="
, mk "rtd" "http://readthedocs.org/search/project/?q="
, mk "null" "http://nullege.com/codes/search/"
, mk "sf" "http://sourceforge.net/search/?q="
, mk "acm" "https://dl.acm.org/results.cfm?query="
, mk "math" "http://mathworld.wolfram.com/search/?query="
]
multi = S.namedEngine "multi" $ foldr1 (S.!>) engines

{-
- Topic
-}

data TopicItem = TI { topicName :: Topic
, topicDir :: Dir
, topicAction :: X ()
, topicIcon :: FilePath
}

myTopicNames :: [Topic]
myTopicNames = map topicName myTopics

myTopicConfig :: TopicConfig
myTopicConfig = TopicConfig
{ topicDirs = M.fromList $ map (\(TI n d _ _) -> (n,d)) myTopics
, defaultTopicAction = const (return ())
, defaultTopic = "web"
, maxTopicHistory = 10
, topicActions = M.fromList $ map (\(TI n _ a _) -> (n,a)) myTopics
}

myIcons = M.fromList $ map (\(TI n _ _ i) -> (n,i)) myTopics

myTopics :: [TopicItem]
myTopics =
[ TI "web" "" (spawn "google-chrome") "firefox.xpm"
, TI "code" "" (spawn "/usr/bin/gvim") "gvim.xpm"
, TI "term" "" (urxvt "tmux attach -t default") "xterm.xpm"
, TI "doc" "Documents/" (spawn "evince") "evince.xpm"
, TI "office" "Documents/" (return ()) "libreoffice34-base.xpm"
, TI "news" "" (urxvt "newsbeuter") "irssi.xpm"
, TI "mail" "" (urxvt "mutt" >> spawn "killall -WINCH mutt") "thunderbird.xpm"
, TI "dict" "" (spawn "goldendict") "goldendict.xpm"
, TI "media" "" (return ()) "imagemagick.xpm"
, TI "emacs" "" (spawn "emacsclient -c -n") "emacs.xpm"
, TI "net" "" (return ()) "gtk-network.xpm"
]
where
urxvt prog = spawn . ("urxvtc -T "++) . ((++) . head $ words prog) . (" -e "++) . (prog++) $ ""


myCommands =
[ ("getmail", namedScratchpadAction scratchpads "getmail")
, ("wallpaper", safeSpawn "change-wallpaper" [])
, ("fade", fadePrompt myXPConfig)
]

fadePrompt xpc = withFocused $ \w -> do
mkXPrompt (TitledPrompt "fade to") xpc (\s -> return [show x | x <- [0..10], s `isPrefixOf` show x]) $ \i -> do
let v = read i :: Int
FadeState u s <- XS.get
XS.put . FadeState u $ if all isDigit i && 0 <= v && v <= 10
then M.insert w (toRational v/10) s
else M.delete w s


data TitledPrompt = TitledPrompt String

instance XPrompt TitledPrompt where
showXPrompt (TitledPrompt t) = t ++ ": "
commandToComplete _ c = c
nextCompletion _ = getNextCompletion

mkCommandPrompt :: XPConfig -> [(String, X ())] -> X ()
mkCommandPrompt xpc cs = do
mkXPrompt (TitledPrompt "Command") xpc compl $ \i -> whenJust (find ((==i) . fst) cs) snd
where
compl s = return . filter (searchPredicate xpc s) . map fst $ cs

mainCommandPrompt xpc = do
defs <- defaultCommands
mkCommandPrompt xpc $ nubBy ((==) `on` fst) $ myCommands ++ defs

getFilesWithExt :: [String] -> String -> IO [String]
getFilesWithExt exts s = fmap lines $ runProcessWithInput "sh" [] ("ls -d -- " ++ s ++ "*/ " ++ s ++ "*." ++ f ++ "\n")
where
f = if length exts == 1 then head exts else ('{':) . (++"}") $ intercalate "," exts

{- | Get the user's response to a prompt an launch an application using the
input as command parameters of the application.-}
launchApp :: XPConfig -> String -> [String] -> X ()
launchApp config app exts = mkXPrompt (TitledPrompt app) config (getFilesWithExt exts) $ launch app
where
launch :: MonadIO m => String -> String -> m ()
launch app params = spawn $ app ++ " " ++ completionToCommand (undefined :: Shell) params