Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

MC Context Sensitive User Menu

News Orthodox File Managers Recommended Links Recommended Papers OFM Book mcedit- Midnight Commander editor mcview
Macro Substitution Command line and command window User Menu Extension menu Colorizing External panelize History of commands
Cheetsheet OFM Standards OFM Standard 1999  Tips MC History Humor Etc

The shell is a powerful software development tool whose utility is hard to overestimate. Shell scripting is an integral part of just about everything system administrators do.

One of the most interesting innovation of Orthodox file managers was so called user menu. It is similar to Windows Start button which was created ten years later but still it is more flexible because items that are displayed in it depends on the context (type of the current file, the presence of highlighted files in the current  panel, etc).

The file manager includes a special file where you can store your scripts. This file can be automatically generated (assembled) from individual components that can be tested separately using make.

The user menu is a menu of useful actions that can be customized by the user. When you access the user menu, the file .mc.menu from the current directory is used if it exists, but only if it is owned by user or root and is not world-writable. If no such file found, ~/.mc/menu is tried in the same way, and otherwise mc uses the default system-wide menu /etc/mc/mc.menu (in version 4.8 and up)

Lines that start with anything but space or tab are considered entries for the menu (in order to be able to use it like a hot key, the first character should be a letter). All the lines that start with a space or a tab are the commands that will be executed when the entry is selected.

Comments are started with #. The additional comment lines must start with #, space or tab.

The structure of the user menu

The format of the menu file is very simple: items are separated with the blank line(s) and consist of blocks of indented line with a header:

Let's look into a simple example:

i   Display ipconfig information
    ifconfig -a

I   Display ipconfig man page
    man ifconfig 

In this case we see two menu items with headers consisting of a single like and containing no visibility predicates. That means that those items will always be displayed in the menu.  You can use macrovariables as ordinary shell variables

X Extract the contents of a compressed tar file

    tar xzvf %f

Here is a more interesting example that uses %D macrosymbol: 

J Copy current directory to other panel recursively

    tar cf - . | (cd %D && tar xvpf -)

The menu can also contains comment blocks that are started with '#'. The additional comment lines must start  space or tab.  That permit temporary deletion of the items from the menu

This is essentially the functionality similar to Windows Start menu. Although it was invented before Windows (in 1986 with version 1.p0 of Norton Commander it is more flexible as entries are arbitrary scripts..  But what makes is far superior is visibility predicated and ability to use macrovariables. With visibility predicates instead of one static menu MC users set a set of different menues depending of context exisating in the panel. For example if the panel does not conatin selected files all entries related to this context will be excluded.

There is also ability to overwrite more global entries with more local, specialised entries.  When the user presses F2, mc checks in three places to find a menu,. The first found menu is used:

The fact that mc checks for ownership and rights provide the possibility dynamically switch from the user menu to system wide menu and back: to hide user menu from the path all you need is just to change permission to 000. 

Let's look into slightly more complicated example:

v     Edit the current file using vim 
       vim %f

V     Edit all selected
       vim %t

It is clear that if there are selected files we probably do not need the item that edits a single file and we can both mark with the same hotkey "v". 

Visibility Conditions

Visibility conditions (or simply conditions) is a method of hiding "irrelevant" items from the user menu invented and implemented in Midnight Commander. The current implementation is ad hoc, but possibly can be reworked and in future based on LUA or some other macro language with standard library.

For example, if particular menu item works only with selected files on active panel, there is a capability to hide this element in "displayed user menu" (which is dynamic and is subset of items defined in user menu) when no selected files in present on active panel.  And if particular element of the panel works only with tar and gtz archive, it is possible to specify that it is excluded if the current file does not have a suitable extension. In way this is a generalization of extensions menu to each item of the user menu.  

MC  "visibility conditions" should preceded the line that specifes the hotkey. Condition starts with single special character.

You can combine default and addition conditions by starting condition with += or =+ (or +=? or =+? if you want debug trace). If you want to use two different conditions, one for adding and another for defaulting, you can precede a menu entry with two condition lines, one starting with + and another starting with =

Conditions syntax

Condition syntax:
  <cond>          = <sub-cond>
  or:		  = <cond> | <cond> ...
  or:		  = <cond> & <cond> ...

Sub-condition is one of following:

f <pattern>	current file matching pattern
F <pattern>	other file matching pattern
d <pattern>	current directory matching pattern
D <pattern>	other directory matching pattern
t <type>	current file of type
T <type>	other file of type
! <sub-cond>	negate the result of sub-condition

Pattern is a normal shell pattern or a regular expression, according to the shell patterns option. You can override the global value of the shell patterns option by writing shell_patterns=x on the first line of the menu file (where "x" is either 0 or 1).

Type is one or more of the following characters:

For example rlf means either regular file, link or fifo. The t type is a little special because it acts on the panel instead of the file. The condition t t is true if there are tagged files in the current panel and false if not.

If the condition starts with =? instead of = a debug trace will be shown whenever the value of the condition is calculated.

The conditions are calculated from left to right. This means

= f *.tar.gz | f *.tgz & t n
is calculated as
( (f *.tar.gz) | (f *.tgz) ) & (t n)

Here is previous example reworks to use conditions. Note that we use negation of the condition "presence of tagged file" in the second menu entry.

shell_patterns=0

+ t t
V     Edit all selected
      vim %t

+ ! t t
v     Edit the current file (type file)  
      vim %f

Here is another, more complex example of the use of conditions:

= f *.tar.gz | f *.tgz & t n
L	List the contents of a compressed tar-archive
	gzip -cd %f | tar xvf -

Visibility predicates blocks

You can program a series of conditions like a construct that resembles a case statement in shell. We will call this construct "visibility predicate block". The block consists of the main condition (that is specified with = sign) and one of more (often applicable only to files with the extensions specified in the main visibility predicate) sub conditions specified with "+" sign. If the main condition is false all menu items with sub conditions are skipped. If it is true than each sub condition is evaluated in addition to the main visibility predicate and if it is true the menu item is included in the menu. 

The typical usage is to distinguish between cases when there are selected files on the panel and cases when there is no such files.

Here is example of  mc.menu with  default visibility condition that specify several type of file that are processed in subsequent menu items.

= f \.pl | f \.sh | f \.ksh | f ^\.
+ t r & ! t t
5       prettyprint
        case %f in
	  *.pl perl -d %f;;
	  *.sh python bashlint     D="`basename %f .tgz`";;
	  *.tcl)    D="`basename %f .tpz`";;
	  *.sh)  D="`basename %f .tar.Z`";;
	  *.ksh)  D="`basename %f .tar.z`";;
	  *.tar.bz2) D="`basename %f .tar.bz2`"; set bunzip2 -c ;;
	  *.tar.F) D="`basename %f .tar.F`"; set freeze -dc;
	esac
6       check syntax
        case %f in
	  *.pl perl -c %f;;
	  *.sh python bashlint     D="`basename %f .tgz`";;
	  *.tcl)    D="`basename %f .tpz`";;
	  *.sh)  D="`basename %f .tar.Z`";;
	  *.ksh)  D="`basename %f .tar.z`";;
	  *.tar.bz2) D="`basename %f .tar.bz2`"; set bunzip2 -c ;;
	  *.tar.F) D="`basename %f .tar.F`"; set freeze -dc;
	esac

+ t r & ! t t
a       Append file to opposite
    	cat %f >>%D/%f

+ t t
A       Append files to opposite files
    	set %u
    	while [ -n "$1" ]; do
      		cat $1 >>%D/$1 || echo tag $1 >>$MC_CONTROL_FILE
      		shift
    	done

+ t r & ! t t
d       Delete file if a copy exists in the other directory.
    	if [ "%d" = "%D" ]; then
      		echo "The two directores must be different"
      		exit 1
    	fi
    	if [ -f %D/%f ]; then        # if two of them, then
        	if cmp -s %D/%f %f; then
        	    	rm %f && echo %f: DELETED
       		else
        		echo "%f and %D/%f differ: NOT deleted"
            		echo -n "Press RETURN "
            		read key
		fi
    	else
      		echo %f: No copy in %D/%f: NOT deleted.
        fi

+ t t
D       Delete tagged files if a copy exists in the other directory.
    if [ "%d" = "%D" ]; then
      echo "The two directores must be different"
      exit 1
    fi 
        for i in %t
        do 
          if [ -f %D/$i ]; then
            SUM1="`sum $i`"
            SUM2="`sum %D/$i`"
            if [ "$SUM1" = "$SUM2" ]; then
          rm $i && echo ${i}: DELETED
        else
          echo $i and %D/$i differ: NOT deleted.
        fi
      else
        echo %f has no copy in %D/%f: NOT deleted.
          fi
        done

The first subcondition is

+ t r

 That means that the corresponding menu item will be included in the menu if and only if  the current file is a regular file.

The second condition is + t t and means that one or several selected files exists in the active panel. In this case we will perform operation of the selected files instead of the current file.

Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: February 10, 2017