Icons for indicating layouts in XMobar (XMonad) - xmonad

I know XMobar supports bitmap icons and I was able to configure those. However I also want to use icons for indicating current XMonad layout, but XMobar gets it on stdin from XMonad. And I couldn't figure out a way to pass bitmap icons instead of regular symbols.
So how one would pass icons instead of symbols for indicating XMonad layout in XMobar?
My current part of config relative to layouts:
defaultLayouts = smartBorders(avoidStruts(
renamed [Replace "R"] (ResizableTall 1 (3/100) (1/2) [])
||| renamed [Replace "R!"] (Mirror (ResizableTall 1 (3/100) (1/2) []))
||| renamed [Replace "F"] (noBorders Full)
||| renamed [Replace "#"] (Grid)
||| renamed [Replace "3C"] (ThreeColMid 1 (3/100) (3/4))
||| renamed [Replace "O"] (Circle)))
chatLayout = renamed [Replace "Chat"]
$ avoidStruts $ withIM (0.2) isPidgin
$ reflectHoriz $ withIM (0.2) isSkype (Grid)
where
isSkype = (Title "zoresvit - Skype™")
isPidgin = (Title "Buddy List")
fullLayout = renamed [Replace "F"] $ avoidStruts $ noBorders $ (Full)
myLayouts = onWorkspace "η" chatLayout $ defaultLayouts
main = do
xmproc <- spawnPipe "xmobar ~/.xmobarrc"
xmonad $ withUrgencyHook NoUrgencyHook $ defaultConfig {
borderWidth = myBorderWidth
, focusedBorderColor = myFocusedBorderColor
, handleEventHook = fullscreenEventHook
, layoutHook = myLayouts
, manageHook = manageHook defaultConfig
<+> composeAll myManagementHooks
<+> manageDocks
, modMask = myModMask
, normalBorderColor = myNormalBorderColor
, startupHook = do
spawn "~/.xmonad/startup_hook.sh"
, terminal = myTerminal
, workspaces = myWorkspaces
, logHook = dynamicLogWithPP $ xmobarPP {
ppOutput = hPutStrLn xmproc
, ppCurrent = xmobarColor solarizedGreen "" . wrap myCurrentWSLeft myCurrentWSRight
, ppHidden = xmobarColor solarizedBase0 ""
, ppHiddenNoWindows = xmobarColor solarizedBase02 ""
, ppLayout = xmobarColor solarizedCyan ""
, ppTitle = xmobarColor solarizedBase1 "" . shorten myTitleLength
, ppUrgent = xmobarColor solarizedRed "" . wrap myUrgentWSLeft myUrgentWSRight
, ppVisible = xmobarColor solarizedBase01 "" . wrap myVisibleWSLeft myVisibleWSRight
}
} `additionalKeys` myKeyBindings

As an alternate suggestion, you can change how XMonad displays the Layout titles. First, change the line
, ppLayout = xmobarColor solarizedCyan ""
to read
, ppLayout = xmobarColor solarizedCyan "" . myLayoutPrinter
Then, add the following function somewhere in your file:
myLayoutPrinter :: String -> String
myLayoutPrinter "Full" = "<icon=layout_full.xbm/>"
myLayoutPrinter "Tall" = "<icon=layout_tall.xbm/>"
myLayoutPrinter "Mirror Tall" = "<icon=layout_mirror_tall.xbm/>"
myLayoutPrinter x = x
Obviously, you'll need to customize the names of the layouts that you use, as well as the icon names.
In theory, you could even take it a step further, if you wanted to get really gaudy and give each layout its own colour. You'd actually simplify the ppLayout line down to
, ppLayout = myLayoutPrinter
The added the custom colours into myLayoutPrinter
myLayoutPrinter :: String -> String
myLayoutPrinter "Full" = xmobarColor "red" "" "<icon=layout_full.xbm/>"
myLayoutPrinter "Tall" = xmobarColor "green" "" "<icon=layout_tall.xbm/>"
myLayoutPrinter "Mirror Tall" = xmobarColor "blue" "" "<icon=layout_mirror_tall.xbm/>"
myLayoutPrinter x = xmobarColor "white" "" x

Just add this to your xmonad.hs:
import XMonad.Layout.Named
myLayout = named "<icon=/home/foo/bar/icon.xpm/>" $ ResizableTall 1 (3/100) (1/2) []

Related

Xmonad Layout Follow up

This is a follow up to a question that I had before. I know about the DoRectFloat/RationalRect modules and such, but, I've tried to write proper Haskell and it either doesn't compile, or it compiles and doesn't do what I want.
(These are floating windows that I want) What I want is a layout like
How would I go about writing this?
My current Xmonad Config:
--my XMonad Config
--xterm, contrib, feh, and nitrogen are used here
import XMonad
import Data.Monoid
import XMonad.Util.Run
import XMonad.Layout.Gaps
import XMonad.Util.SpawnOnce
import XMonad.Layout.Spacing
import System.Exit
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.ManageHook
import qualified DBus as D
import qualified DBus.Client as D
import XMonad.Hooks.DynamicLog
import qualified Codec.Binary.UTF8.String as String
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Graphics.X11.ExtraTypes.XF86
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal = "xterm"
-- Whether focus follows the mouse pointer.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
-- Whether clicking on a window to focus also passes the click to the window
myClickJustFocuses :: Bool
myClickJustFocuses = False
-- Width of the window border in pixels.
--
myBorderWidth = 2
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask = mod1Mask
-- The default number of workspaces (virtual screens) and their names.
-- By default we use numeric strings, but any string may be used as a
-- workspace name. The number of workspaces is determined by the length
-- of this list.
--
-- A tagging example:
--
-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9]
--
myWorkspaces = ["1","2","3","4","5","6","7","8","9"]
-- Border colors for unfocused and focused windows, respectively.
--
myNormalBorderColor = "#0a0b11"
myFocusedBorderColor = "#ace5e0"
--soda
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf#(XConfig {XMonad.modMask = modm}) = M.fromList $
-- launch a terminal
[ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
-- launch dmenu
, ((modm, xK_d ), spawn "dmenu_run")
--launch ff
, ((modm, xK_p ), spawn "brave")
--vol
, ((modm, xK_F8 ), spawn "pactl set-sink-mute #DEFAULT_SINK# toggle")
, ((modm, xK_i ), spawn "pactl set-sink-port 0 analog-output-speaker")
, ((modm, xK_o ), spawn "pactl set-sink-port 0 analog-output-headphones")
, ((modm, xK_F6 ), spawn "pactl set-sink-volume #DEFAULT_SINK# 50%")
, ((modm, xK_Up ), spawn "pactl set-sink-volume #DEFAULT_SINK# +3%")
, ((modm, xK_Down ), spawn "pactl set-sink-volume #DEFAULT_SINK# -3%")
--, ((0, xK_Right), spawn "xbacklight -dec 10")
--, ((0, xK_Left), spawn "xbacklight -inc 10")
--lol
, ((0, xF86XK_AudioRaiseVolume ), spawn "pactl set-sink-volume #DEFAULT_SINK# +5%")
, ((0, xF86XK_AudioLowerVolume ), spawn "pactl set-sink-volume #DEFAULT_SINK# -5%")
, ((0, xF86XK_AudioMute ), spawn "pactl set-sink-mute #DEFAULT_SINK# toggle")
-- launch gmrun
--, ((modm .|. shiftMask, xK_p ), spawn "gmrun")
, ((modm .|. shiftMask, xK_v ), spawn "virtualbox")
, ((modm .|. shiftMask, xK_b ), spawn "xrandr --output eDP-1 --brightness 0.5")
, ((modm .|. shiftMask, xK_z ), spawn "xrandr --output eDP-1 --brightness 1")
--master settings /gnome
, ((modm .|. shiftMask, xK_f ), spawn "gnome-control-center")
--eq
, ((modm .|. shiftMask, xK_u ), spawn "pulseeffects")
--lock (you need i3lock installed on your system)
, ((modm .|. shiftMask, xK_x ), spawn "i3lock -i ~/.config/i3/spart.png")
--fm
, ((modm .|. shiftMask, xK_g ), spawn "pcmanfm")
-- close focused window
, ((modm .|. shiftMask, xK_c ), kill)
-- Rotate through the available layout algorithms
, ((modm, xK_space ), sendMessage NextLayout)
-- Reset the layouts on the current workspace to default
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ), refresh)
-- Move focus to the next window
, ((modm, xK_Tab ), windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ), windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ), windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ), windows W.focusMaster )
-- Swap the focused window and the master window
, ((modm, xK_Return), windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ), windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ), windows W.swapUp )
-- Shrink the master area
, ((modm, xK_h ), sendMessage Shrink)
-- Expand the master area
, ((modm, xK_l ), sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ), withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm , xK_comma ), sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period), sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap
-- Use this binding with avoidStruts from Hooks.ManageDocks.
-- See also the statusBar function from Hooks.DynamicLog.
--
-- , ((modm , xK_b ), sendMessage ToggleStruts)
-- Quit xmonad
, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Restart xmonad
, ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart")
-- Run xmessage with a summary of the default keybindings (useful for beginners)
, ((modm .|. shiftMask, xK_slash ), spawn ("echo \"" ++ help ++ "\" | xmessage -file -"))
]
++
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
------------------------------------------------------------------------
-- Layouts:
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout = tiled ||| Mirror tiled ||| theg ||| Full
where
tiled = spacing 35 $ Tall nmaster delta ratio
theg = gaps [(U,18), (R,23)] $ Tall 1 (3/100) (1/2)
nmaster = 1
ratio = 1/2
delta = 3/100
------------------------------------------------------------------------
-- Window rules:
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
-- --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)
myManageHook = composeAll . concat $
[ [className =? "mpv" --> doFloat]
, [className =? "xterm" --> (doRectFloat $ W.RationalRect 0.5 0.5 0.4 0.4)]
--, [className =? c --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)| c <- mylol]
, [manageDocks]
]
where
myTop = ["xterm htop"]
myTerm = ["xterm"]
myVis = ["xterm vis"]
------------------------------------------------------------------------
-- Event handling
-- * EwmhDesktops users should change this to ewmhDesktopsEventHook
--
-- Defines a custom handler function for X Events. The function should
-- return (All True) if the default handler is to be run afterwards. To
-- combine event hooks use mappend or mconcat from Data.Monoid.
--
myEventHook = mempty
------------------------------------------------------------------------
-- Status bars and logging
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'XMonad.Hooks.DynamicLog' extension for examples.
--
myLogHook = return ()
------------------------------------------------------------------------
-- Startup hook
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
myStartupHook :: X ()
myStartupHook = do
spawn "nitrogen --restore &"
spawn "picom &"
spawn "xterm vis"
spawn "xsetroot -cursor_name left_ptr"
spawn "xset b off"
------------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
-- Run xmonad with the settings you specify. No need to modify this.
--
main = do
xmproc <- spawnPipe "xmobar -x 0 ~/.xmonad/taskbarrc"
xmonad $ docks defaults
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
defaults = def {
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
clickJustFocuses = myClickJustFocuses,
borderWidth = myBorderWidth,
modMask = myModMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
-- hooks, layouts
layoutHook = myLayout,
manageHook = myManageHook,
handleEventHook = myEventHook,
logHook = myLogHook,
startupHook = myStartupHook
}
-- | Finally, a copy of the default bindings in simple textual tabular format.
help :: String
help = unlines ["The default modifier key is 'alt'. Default keybindings:",
"",
"-- launching and killing programs",
"mod-Shift-Enter Launch xterminal",
"mod-p Launch dmenu",
"mod-Shift-p Launch gmrun",
"mod-Shift-c Close/kill the focused window",
"mod-Space Rotate through the available layout algorithms",
"mod-Shift-Space Reset the layouts on the current workSpace to default",
"mod-n Resize/refresh viewed windows to the correct size",
"",
"-- move focus up or down the window stack",
"mod-Tab Move focus to the next window",
"mod-Shift-Tab Move focus to the previous window",
"mod-j Move focus to the next window",
"mod-k Move focus to the previous window",
"mod-m Move focus to the master window",
"",
"-- modifying the window order",
"mod-Return Swap the focused window and the master window",
"mod-Shift-j Swap the focused window with the next window",
"mod-Shift-k Swap the focused window with the previous window",
"",
"-- resizing the master/slave ratio",
"mod-h Shrink the master area",
"mod-l Expand the master area",
"",
"-- floating layer support",
"mod-t Push window back into tiling; unfloat and re-tile it",
"",
"-- increase or decrease number of windows in the master area",
"mod-comma (mod-,) Increment the number of windows in the master area",
"mod-period (mod-.) Deincrement the number of windows in the master area",
"",
"-- quit, or restart",
"mod-Shift-q Quit xmonad",
"mod-q Restart xmonad",
"mod-[1..9] Switch to workSpace N",
"",
"-- Workspaces & screens",
"mod-Shift-[1..9] Move client to workspace N",
"mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3",
"mod-Shift-{w,e,r} Move client to screen 1, 2, or 3",
"",
"-- Mouse bindings: default actions bound to mouse events",
"mod-button1 Set the window to floating mode and move by dragging",
"mod-button2 Raise the window to the top of the stack",
"mod-button3 Set the window to floating mode and resize by dragging"]
When starting the three windows, use xterm's -class option to modify the WM_CLASS property it attaches to its window, choosing a different and unique class for each of the three. Then you can select for that class in your manage hook to only match the right window.

Execute code beyond original screen view with Vim to R using GNU Screen

I'm using GNU Screen to send code from Vim to R with the following .vimrc configuration:
map <C-L> "kyy:echo system("screen -S $STY -p R -X stuff ".shellescape(#k))<CR>j
vmap <C-L> "xy:echo system("screen -S $STY -p R -X stuff ".shellescape(#x."\n"))<CR>j
(I use cntr-L to send code from Vim to my R window titled "R".)
I can run functions within the current screen,
exp_val <- function(roll){
vals <- numeric(length(roll))
vals[roll == "G"] <- 1/6
vals[roll == "Y"] <- 1/3
vals[roll == "R"] <- 1/2
sum(vals)
}
prob_choice <- function(roll, ng = 6, ny = 4, nr = 3){
tot <- ng + ny + nr
i <- c(ng,ny,nr)
col <- c("G","Y","R")
p1 <- i[col==roll[1]]/tot
i[col==roll[1]] <- i[col==roll[1]] - 1
p2 <- i[col==roll[2]]/(tot-1)
i[col==roll[2]] <- i[col==roll[2]] - 1
p3 <- i[col==roll[3]]/(tot-2)
p1*p2*p3
}
but when I try to scroll down and highlight another function that extends below the original screen view
single_round <- function(sampsp,probs=rep(1/nrow(sampsp),nrow(sampsp))){
r <- sample(1:nrow(sampsp),1,prob = probs)
dice <- sampsp[r,]
roll <- numeric(3)
i <- which(dice=="G"); roll[i] <- sample(c("B","S","F"),1,prob = c(1/2,1/6,1/3))
j <- which(dice=="Y"); roll[j] <- sample(c("B","S","F"),1,prob = c(1/3,1/3,1/3))
k <- which(dice=="R"); roll[k] <- sample(c("B","S","F"),1,prob = c(1/6,1/2,1/3))
num_dice <- c(length(i),length(j),length(k))
outcome <- c(sum(roll=="B"),sum(roll=="S"),sum(roll=="F"))
if (is.null(roll[i])){roll[i] <- 0}
if (is.null(roll[j])){roll[j] <- 0}
if (is.null(roll[k])){roll[k] <- 0}
feet <- c(sum(roll[i]=="F"),sum(roll[j]=="F"),sum(roll[k]=="F")) # to keep track of color of footprints
list(num_dice,outcome,feet)
}
I get the following error
X: stuff: one or two arguments required
Is there anything I can change in my .vimrc so I can highlight and execute a large part of the script that extends beyond the original screen view?

Why is X library reporting wrong string length values?

I was trying to get the width of the string, using XTextWidth() function, but for some reason the returned value is always bigger than the actual displayed length of string. In the following example, the value printed out is 196, while if I measure the width on-screen, it's somewhere around 168 pixels (the following is compilable and runnable example):
import Control.Concurrent
import qualified Graphics.X11.Xlib as X
import qualified Graphics.X11.Xlib.Types as Xt
import qualified Graphics.X11.Types as Xt
main = do
display <- X.openDisplay ""
let dflt = X.defaultScreen display
border = X.blackPixel display dflt
background = X.whitePixel display dflt
rootw <- X.rootWindow display dflt
win <- X.createSimpleWindow display rootw 0 0 500 300 1 border background
X.mapWindow display win
X.moveWindow display win 0 0
updateScreen display win
updateScreen display win = do
gc <- X.createGC display win
bgcolor <- initColor display "white"
fgcolor <- initColor display "black"
X.setBackground display gc bgcolor
X.setForeground display gc fgcolor
font <- X.loadQueryFont display "-misc-fixed-*-*-*-*-14-*-*-*-*-*-*"
let str = "Some reasonably long string."
len = X.textWidth font str
putStrLn $ show len
X.drawImageString display win gc 0 50 str
X.freeFont display font
X.freeGC display gc
threadDelay 100000
updateScreen display win
initColor :: X.Display -> String -> IO X.Pixel
initColor dpy color = do
let colormap = X.defaultColormap dpy (X.defaultScreen dpy)
(apros,_) <- X.allocNamedColor dpy colormap color
return $ X.color_pixel apros
How can I fix it?
You are not displaying with the selected font. Try this:
X.setFont display gc $ X.fontFromFontStruct font

Use character string as function argument

I'm sure this is simple, but I cannot find a solution ...
I would like to use a variable containing a character string as argument for a function.
x <- c(1:10)
myoptions <- "trim=0, na.rm=FALSE"
Now, something like
foo <- mean(x, myoptions)
should be the same as
foo <- mean(x, trim=0, na.rm=FALSE)
Thanks in advance!
You can use eval and parse:
foo <- eval(parse(text = paste("mean(x,", myoptions, ")")))
A more natural way to do what you want is to use do.call. For example,
R> l[["trim"]] = 0
R> l[["na.rm"]] = FALSE
R> l[["x"]] = 1:10
##Or l <- list(trim = 0, na.rm = FALSE, x = 1:10)
R> do.call(mean, l)
[1] 5.5
If for some reason you really want to use a myoptions string, you could always use strsplit to coarce it into a list form. For example,
R> y = "trim=0, na.rm=FALSE"
R> strsplit(y, ", ")
[[1]]
[1] "trim=0" "na.rm=FALSE"
R> strsplit(y, ", ")[[1]][1]
[1] "trim=0"
Here's a third answer that both uses parse, alist and do.call. My motivation for this new answer, is in the case where arguments are passed interactively from a client-side as chars. Then I guess, there is no good way around not using parse. Suggested solution with strsplit, cannot understand the context whether a comma , means next argument or next argument within an argument. strsplit does not understand context as strsplit is not a parser.
here arguments can be passed as "a=c(2,4), b=3,5" or list("c(a=(2,4)","b=3","5")
#' convert and evaluate a list of char args to a list of arguments
#'
#' #param listOfCharArgs a list of chars
#'
#' #return
#' #export
#'
#' #examples
#' myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
#' myArgs = callMeMaybe(myCharArgs)
#' do.call(mean,myArgs)
callMeMaybe2 = function(listOfCharArgs) {
CharArgs = unlist(listOfCharArgs)
if(is.null(CharArgs)) return(alist())
.out = eval(parse(text = paste0("alist(",
paste(parse(text=CharArgs),collapse = ","),")")))
}
myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
myArgs = callMeMaybe2(myCharArgs)
do.call(mean,myArgs)
[1] 2
Using all of do.call, eval and parse (combining kohske's and csgillespie's answers, and also WoDoSc's answer to 'Pass a comma separated string as a list'):
x <- c(1:10)
myoptions <- "trim = 0, na.rm = FALSE"
do.call(
what = mean,
args = append(list(x = x), eval(parse(text = paste0("list(", myoptions, ")"))))
)
This solution can be quite resilient in a more complex case, such as shown below.
myfn <- function(x, y = 0, z = 0, ...) {
print(paste("x:", x))
print(paste("y:", y))
print(paste("z:", z))
if (length(list(...)) > 0) {
print("other:")
print(list(...))
}
}
myextraargs <- paste(
"y = c(11, 14), z = 47,",
"t = data.frame(p = c('apple', 'plum'), j = c(7, 2), k = c(3, 21))"
)
do.call(
what = myfn,
args = append(
list(x = 7),
eval(parse(text = paste0("list(", myextraargs, ")")))
)
)
results in:
[1] "x: 7"
[1] "y: 11" "y: 14"
[1] "z: 47"
[1] "other:"
$t
p j k
1 apple 7 3
2 plum 2 21
...and...
myextraargs <- NULL
do.call(
what = myfn,
args = append(
list(x = 7),
eval(parse(text = paste0("list(", myextraargs, ")")))
)
)
results in
[1] "x: 7"
[1] "y: 0"
[1] "z: 0"

gtk2hs: Request recalculation of windows size after removing a widget

I have a Window with three Entry widgets and one Button. I use the button to remove one of the widgets programmatically. The problem is that the main window doesn't change it's size to fit the new layout after it's been removed.
I can imagine that I need to send some Signal or Event to the main loop which would cause the recalculation but I've been unable to find such functionality.
Here is some example code:
import Graphics.UI.Gtk
import Data.IORef
import qualified Graphics.UI.Gtk as G hiding (Point)
import qualified Graphics.UI.Gtk.Gdk.EventM as E
import qualified Graphics.UI.Gtk.Abstract.Widget as W
import qualified Graphics.Rendering.Cairo as C
makeEntry :: String -> IO Entry
makeEntry str = do e <- entryNew
entrySetText e str
return e
main :: IO ()
main = do
initGUI
window <- windowNew
box <- vBoxNew False 0
G.on window G.keyPressEvent $ E.tryEvent $ do
"Escape" <- E.eventKeyName
C.liftIO $ G.widgetDestroy window
set window [ containerChild := box ]
e1 <- makeEntry "e1"
boxPackStart box e1 PackNatural 0
e2 <- makeEntry "e2"
boxPackStart box e2 PackNatural 0
e3 <- makeEntry "e3"
boxPackStart box e3 PackNatural 0
button <- buttonNew
set button [ buttonLabel := "Remove" ]
boxPackStart box button PackNatural 0
onClicked button (containerRemove box e2)
onDestroy window mainQuit
widgetShowAll window
mainGUI
You can ask your top-level window how big it wants to be, and make it be that big:
refresh window = do
Requisition w h <- widgetSizeRequest window
windowResize window w h
To use this, stick it in the button's click-handler:
onClicked button (containerRemove box e2 >> refresh window)

Resources