Bash : navigateur de fichiers (Ncurse like) pour l’auto complétion

closeCet article a été publié il y a 1 an 6 mois 3 jours, il est donc possible qu’il ne soit plus à jour. Les informations proposées sont donc peut-être expirées.

kokoko3k un utilisateur d’Archlinux a eu l’idée d’ajouter à bash un navigateur de fichiers pour l’auto complétion.
Connaissant le langage gambas (basic pour Linux) il a donc commencé à développer dans ce langage, sous le nom de KingBash, une interface graphique apportant cette fonctionnalité.

Ci-dessous une capture d’écran du résultat :

kingBash GAMBAS

Intéressé par un outil similaire mais totalement en ligne de commande (Ncurse) Procyon un autre membre des forums Archlinux s’est attaqué au développement d’une version dans le style Ncurse.

Ci-dessous la dernière version de son projet en python (version 23 maj le 08/08/2010):
(Ce code est disponible sur pastebin)

version 23
version 22
version 21
version 20
version 19
version 18

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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
#! /usr/bin/env python
import os, os.path, re, stat, termios, fcntl, sys, string, operator, struct
 
def usage_help_text():
	print """Usage
Tab Completion:
 
function kingbash.fn() {
  echo -n "KingBash> $READLINE_LINE" #Where "KingBash> " looks best if it resembles your PS1, at least in length.
  OUTPUT=`"""+sys.argv[0]+""" "$(compgen -ab -A function)"`
  READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
  READLINE_LINE=`echo "$OUTPUT" | head -n -1`
  echo -ne "\\r\\e[2K"; }
bind -x '"\\t":kingbash.fn'
 
 
History search:
 
function kingbash.hs() {
  echo -n "KingBash> $READLINE_LINE"
  history -a
  OUTPUT=`"""+sys.argv[0]+""" -r <(tac ~/.bash_history)`
  READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
  READLINE_LINE=`echo "$OUTPUT" | head -n -1`
  echo -ne "\\r\\e[2K"; }
bind -x '"\\x12":kingbash.hs'
 
 
CLI dmenu:
 
... | """+sys.argv[0]+"""
 
 
GUI dmenu:
 
rm /tmp/menu
cat > /tmp/inmenu
urxvtc -e bash -c 'export READLINE_POINT=0; answ=$(""" + sys.argv[0] + """ -r /tmp/inmenu | head -n 1); echo -n "$answ" > /tmp/menu'
while sleep 0.1; do [ -f /tmp/menu ] && break; done
cat /tmp/menu
rm /tmp/menu
rm /tmp/inmenu
-------
 
F1 inside the application will print a key table"""
 
def F1_help_text():
	sys.stderr.write("""\x1b[?7hGet usage advice by running """+sys.argv[0]+""" without arguments
-------------------------
There are two modes: Tab completion and History/file/dmenu completion.
---Key table---
+Both modes+
 F1		This help
 Up/Down
 Shift+Up/Down
 Page up/Pagedown
 Home/End	Move around the list
 Enter		Complete the selection and quit
 Any other character is added "as is" (with the escape sequence replaced with ESC).
 Under "Tab completion" the program quits after a space or equals sign.
 
+Tab Completion+
*F2		Erase first word and move cursor to start of line, after the selection has been completed
 Left		Go to the parent directory and continue browsing
 Right		Complete the selection, but if it's a directory, bring up the program again inside that directory
 Escape		Quit, leaving the line as it is seen in the application
 Backspace	Erase the character left of the cursor and complete again
 Alt+Backspace	Same, but an entire word or path
 Control+U	Clear the line and quit
 Insert		Complete the selection, move the selector bar down, and continue as if we are completing the previous selection again
 Asterisk	Add everything in the list to the command line. If there are 'suggestions', only complete those. Quit afterwards.
 
+History Completion+
 Left		Move the cursor left
 Right		Move the cursor right
 Escape		Quit, restore the line to what it was when KingBash started
 Backspace	Erase the character left of the cursor
 Alt+Backspace	Same, but an entire word or path
*Delete		Delete the character under the cursor
 Control+U	Clear the line and continue
*Tab		Make the current line the same as the selection
 Insert		Like Tab
 
* means this key does nothing at all in the other mode
-------------------------
\x1b[?7l""")
 
def main():
	try:
		fd=sys.stdin.fileno()
		oldterm=termios.tcgetattr(fd)
		dmenu_mode=False
		del fd
		del oldterm
	except termios.error: #stdin is a pipe
		dmenu_mode=True
	try:
		point=int(os.environ["READLINE_POINT"])
	except:
		if not dmenu_mode:
			usage_help_text()
			sys.exit(0)
		else:
			point=0
	try:
		line=os.environ["READLINE_LINE"]
	except KeyError:
		line=""
	original_line=line
	original_point=point
	if dmenu_mode or ( len(sys.argv) > 2 and sys.argv[1] == "-r" ):
		if dmenu_mode:
			f=os.fdopen(sys.stdin.fileno())
		else:
			f=open(sys.argv[2])
		file_mode=True
		read_file=[]
		for read_f in f:
			read_file.append(read_f[:-1])
		f.close()
		suggestions=grep_list(line.split(), read_file)
		filedict=[]
		for suggestion in suggestions:
			filedict.append( { "isdir":False, "name":suggestion, "format":"\x1b[m"+suggestion, "rec":False })
		prework=""
		workpath=""
		is_command=True
		upto=""
		workstr=""
		postwork=""
		cursor=point
	else:
		file_mode=False
		if line[-2:] == "..": print line+"/"; print point+1; return
		upto=line[:point]
		first_space=re.search("[^\\\\] ", upto)
		if first_space:
			first_space=first_space.start()
		else:
			first_space=point
		workstr=re.match("(.*(?<!\\\\)[ &;|=])(.*)", upto)
		if not workstr:
			prework=""
			workstr=upto
		else:
			prework=workstr.group(1)
			workstr=workstr.group(2)
		postwork=line[point:]
		workpath=re.match("(.*/)(.*)",workstr)
		if not workpath:
			workpath=""
		else:
			workstr=workpath.group(2)
			workpath=workpath.group(1)
		if len(workstr) != 0  and workstr[0] == "'":
			workstr=unfixshell_singlequote(workstr)
		else:
			workstr=unfixshell(workstr)
		filedict=[]
 
		is_command=False
		if len(workpath) == 0:
			if len(prework) == 0: is_command=True
			else:
				if point <= first_space: is_command=True
				if prework[-5:] in ("sudo ", "type "): is_command=True
				if prework[-6:] in ("which "): is_command=True
				if prework[-7:] in ("whatis "): is_command=True
				if prework[-8:] in ("whereis "): is_command=True
				if prework[-1]  in ("|", ";", "&") : is_command=True
				if prework[-2:] in ("| ","; ","& "): is_command=True
				#However,
				if prework[-1]  == "=" : is_command=False
				if prework[-2:] == "= ": is_comamnd=False
 
		if is_command:
			suggestions=complete_command(workstr)
		else:
			suggestions=complete_filename(workstr, unfixshell(workpath))
		suggestions=sorted(set(suggestions),key=str.lower)
		if len(suggestions) == 1 and not (len(workstr) == 0 and len(sys.argv) > 2 and sys.argv[2] == "rerun" ):
			fix=fixshell(suggestions[0])
			if not os.path.isdir(os.path.expandvars(os.path.expanduser(unfixshell(workpath))) + suggestions[0]):
				fix+=" "
			else:
				fix+="/"
				if len(sys.argv) > 2 and sys.argv[2] == "rerun":
					rerun_fn(prework+workpath+fix+postwork, str(len(prework+workpath+fix)))
			print prework + workpath + fix + postwork
			print len(prework + workpath + fix)
			return
		if len(suggestions) == 0:
			if len(workstr) != 0 or not ( len(sys.argv) > 2 and sys.argv[2] == "rerun" ):
				print line
				print point
				return
			else:
				suggestions=[""]
		if len(workstr) > 0 and workstr[-1] == '\\': workstr=workstr[:-1] #Don't escape the escape for a future character
		first=suggestions[0]
		lcd=[] #find largest common divider
		for last in suggestions[1:]:
			ld=""
			for i in xrange(min(len(first),len(last))):
				if first[i].upper()==last[i].upper():
					ld=ld+first[i]
				else:
					break
			lcd.append(ld)
		if len(lcd) > 0:
			smallest=sorted(lcd)[0]
		else:
			smallest=""
		if len(smallest) > len(workstr):
			workstr=smallest
		line=prework+workpath+fixshell(workstr)+postwork
		point=len(prework+workpath+fixshell(workstr))
		cursor=len(workpath+workstr)
		if is_command:
			for suggestion in suggestions:
				filedict.append({ "isdir":False, "name":suggestion, "format":"\x1b[7m" + suggestion[:cursor] + "\x1b[m" + suggestion[cursor:], "rec":False })
		else:
			for suggestion in suggestions:
				statf=os.lstat(os.path.expandvars(os.path.expanduser(unfixshell(workpath)))+suggestion)
				link_ind=""
				if stat.S_ISLNK(statf[stat.ST_MODE]):
					link_ind=" -> "+os.readlink(os.path.expandvars(os.path.expanduser(unfixshell(workpath)))+suggestion)
					try:
						statf=os.stat(os.path.expandvars(os.path.expanduser(unfixshell(workpath)))+suggestion)
						link_ind=" @"+link_ind
					except OSError:
						link_ind=" @BAD"+link_ind
				size=statf[stat.ST_SIZE]
				exp=0
				while size >= 1024: size=size/1024; exp=exp+1
				size=str(size)+["B","KB","MB","GB","TB"][exp]
				if stat.S_ISDIR(statf[stat.ST_MODE]):
					dirappend="/"
				else:
					dirappend=""
				if point > first_space and len(prework.split()) > 0 and isrecommended(re.sub(".*[^\\\\][;&|]", "", prework).split()[0], suggestion, dirappend=="/"):
					rec=True
					color="\x1b[m\x1b[31m"
					matchcolor="\x1b[31;47m"
				else:
					rec=False
					color="\x1b[m"
					matchcolor="\x1b[30;47m"
				filedict.append({ "isdir":dirappend=="/", "name":suggestion, "format":"\x1b[m"+string.ljust("\x1b[35m(" + size + ")\x1b[m", 17) + matchcolor + str(workpath+suggestion)[:cursor] + color + str(workpath+suggestion)[cursor:] + dirappend + link_ind, "rec":rec})
		filedict.sort(key=operator.itemgetter("isdir"),reverse=True)
		filedict.sort(key=operator.itemgetter("rec"),reverse=True)
 
	selected=0
	viewmin=0
	if len(sys.argv) == 5:
		selected=int(sys.argv[3])
		viewmin=int(sys.argv[4]) #Restoring the position from Insert
	try:
		screen=terminal_size()[0]/3
		if screen == 0: screen=0/0
	except:
		screen=23
	original_screen=screen
 
	count=len(filedict)-1
	if count < screen: screen=count
 
 
	try:
		fd=sys.stdin.fileno()
		oldterm=termios.tcgetattr(fd)
	except termios.error:
		newin=os.open("/dev/tty", os.O_RDONLY)
		os.dup2(newin, fd)
		oldterm=termios.tcgetattr(fd)
	newattr=termios.tcgetattr(fd)
	newattr[3]=newattr[3] & ~termios.ICANON & ~termios.ECHO
	termios.tcsetattr(fd, termios.TCSANOW, newattr)
 
	#This disables line wrap, makes the cursor invisible, and clears the possible calling-function's replacement prompt
	sys.stderr.write("\x1b[?7l\x1b[?25l\r\x1b[2K")
 
	file_mode_changes=False
	show_F1_help_text=False
	rerun=False
	icm=False #icm means Insert's Cursor Move.
 
	try:
		while 1:
			if show_F1_help_text:
				F1_help_text()
				show_F1_help_text=False
			if file_mode and file_mode_changes:
				suggestions=grep_list(line.split(), read_file)
				filedict=[]
				for suggestion in suggestions:
					filedict.append( { "isdir":False, "name":suggestion, "format":"\x1b[m"+suggestion, "rec":False })
				oldcount=count
				count=len(filedict)-1
				if count < 0: count = 0
				if count < original_screen:
					screen=count
				if screen != original_screen and count > original_screen:
					screen=original_screen
				if oldcount != count: selected=0
				file_mode_changes=False
			try:
				unused = line[point+1:]
				sys.stderr.write("KingBash> " + line[:point] + '\x1b[7m' + line[point] + '\x1b[m' + line[point+1:] + '\n')
			except IndexError:
				sys.stderr.write("KingBash> " + line + '\x1b[7m \x1b[m\n')
			show_filelist(filedict, selected, viewmin, screen)
			sys.stderr.write("\n"+"-"*999)
			try:
				c=sys.stdin.read(1)
				if c == "\x1b":
					c="ESC"
					oldflags=fcntl.fcntl(fd, fcntl.F_GETFL)
					fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
					while 1:
						try:
							newc=sys.stdin.read(1)
							c=c+newc
							if newc in ("A","B","C","D","a","b","c","d","~"): #Common endings of escape codes of keys that are held down
								break
						except IOError: break
					fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
				if   c == "ESC[A":#UP
					selected-=1
				elif c in ("ESC[a","ESC[1;2A"):#SHIFT UP
					selected-=5
				elif c == "ESC[B":#DOWN
					selected+=1
				elif c in ("ESC[b","ESC[1;2B"):#SHIFT DOWN
					selected+=5
				elif c == "ESC[C":#RIGHT
					if file_mode:
						if point != len(line):
							point+=1
					else:
						filedict[selected]["name"]=fixshell(filedict[selected]["name"])
						if not filedict[selected]["isdir"]:
							filedict[selected]["name"]+=" "
						else:
							filedict[selected]["name"]+="/"
						line=prework + workpath + filedict[selected]["name"] + postwork
						point=len(prework + workpath + filedict[selected]["name"])
						rerun=True
						break
				elif c == "ESC[D":#LEFT
					if file_mode:
						if point != 0:
							point-=1
					else:
						workstr=""
						oldlen=len(workpath)
						if workpath == "/":
							pass
						elif workpath == "" or workpath[-3:] == "../":
							workpath+="../"
						else:
							oldpath=workpath
							workpath=re.sub("/[^/]*/$", "/", workpath)
							if oldpath == workpath:
								workpath=re.sub(".*?/$", "", workpath)
							del oldpath
						line=prework+workpath+fixshell(workstr)+postwork
						point=point+(len(workpath)-oldlen)
						rerun=True
						break
				elif c == "ESC[6~":#PAGEDOWN
					selected+=screen+1
					if viewmin + screen + 1 < count: viewmin+=screen+1
				elif c == "ESC[5~":#PAGEUP
					selected-=screen+1
					viewmin-=screen+1
				elif c in ("ESC[4~","ESC[F","ESC[8~"):#END
					selected=count
					viewmin=count - (screen - (count % screen))
				elif c in ("ESC[1~","ESC[H","ESC[7~"):#HOME
					selected=0
					viewmin=0
				elif c in ("\x0d", "\n"):#ENTER
					if not file_mode:
						filedict[selected]["name"]=fixshell(filedict[selected]["name"])
						if not filedict[selected]["isdir"]:
							filedict[selected]["name"]+=" "
						else:
							filedict[selected]["name"]+="/"
					try:
						line=prework + workpath + filedict[selected]["name"] + postwork
						point=len(prework + workpath + filedict[selected]["name"])
					except IndexError:
						pass
					break
				elif c == "ESC":#ESCAPE
					if file_mode:
						line=original_line
						point=original_point
					break
				elif c in ("\x7f", "\x08"):#BACKSPACE
					if file_mode:
						if point != 0:
							line=line[:point-1]+line[point:]
							point-=1
							file_mode_changes=True
					else:
						line=prework+str(workpath+workstr)[:-1]+postwork
						point-=1
						rerun=True
						break
				elif c in ("ESC\x7f", "ESC\x08"):#ALT+BACKSPACE
					if file_mode:
						try:
							nline=" ".join(line[:point].split(" ")[:-1])+line[point:]
							point-=len(line)-len(nline)
							line=nline
							del nline
							file_mode_changes=True
						except: pass
					else:
						new=re.sub("""[/ '"]?[^/ '"]*?[/ '"]?$""", "", prework+workpath+fixshell(workstr))
						line=new+postwork
						point=len(new)
						rerun=True
						break
				elif c == "ESC[3~":#DELETE
					if file_mode:
						line=line[:point]+line[point+1:]
						file_mode_changes=True
				elif c == "\x15":#CONTROL + U
					line=""
					point=0
					if not file_mode:
						break
				elif c == "\x09":#TAB
					if file_mode:
						line=filedict[selected]["name"]
						point=len(filedict[selected]["name"])
				elif c == "ESC[2~":#INSERT
					if not file_mode:
						filedict[selected]["name"]=fixshell(filedict[selected]["name"])
						if not filedict[selected]["isdir"]:
							filedict[selected]["name"]+=" "
						else:
							filedict[selected]["name"]+="/ "
					line=prework + workpath + filedict[selected]["name"] + workpath + fixshell(workstr) + postwork
					point=len(prework + workpath + filedict[selected]["name"] + workpath + fixshell(workstr))
					if not file_mode:
						rerun=True
						selected+=1
						if selected > count: selected=count
						if selected > viewmin + screen: viewmin+=screen+1
						icm=(str(selected), str(viewmin))
						break
				elif c == "*" and not file_mode:#ASTERISK
					line=prework
					point=len(prework)
					allfalse=True
					for file in filedict:
						if file["rec"] == False: continue
						allfalse=False
						file["name"]=fixshell(file["name"])+" "
						line+=workpath+file["name"]
						point+=len(workpath+file["name"])
					if allfalse:
						for file in filedict:
							file["name"]=fixshell(file["name"])+" "
							line+=workpath + file["name"]
							point+=len(workpath + file["name"])
#					line+=workpath+fixshell(workstr)+postwork
#					point+=len(workpath+fixshell(workstr))
					line+=postwork
#					rerun=True #In case you want to backspace and add more stuff
					break
				elif c in ("ESC[12~","ESCOQ"):#F2
					if not is_command:
						prework=re.sub("^.*?(?<!\\\\) ", "", prework) #remove first word and move cursor there
						prework=" "+prework
						filedict[selected]["name"]=fixshell(filedict[selected]["name"])
						if not filedict[selected]["isdir"]:
							filedict[selected]["name"]+=" "
						else:
							filedict[selected]["name"]+="/"
						line=prework + workpath + filedict[selected]["name"] + postwork
						point=0
						break
				elif c in ("ESC[11~","ESCOP"):#F1
					show_F1_help_text=True
				else:
					if file_mode:
						line=line[:point] + c + line[point:]
						point+=len(c)
						file_mode_changes=True
					else:
						point=len(prework + workpath + fixshell(workstr) + c)
						line=prework + workpath + fixshell(workstr) + c + postwork
						if c not in (' ',"="):
							rerun=True
						break
			except IOError: pass
			if selected < 0: selected=0
			elif selected > count: selected=count
			elif selected > viewmin + screen: viewmin+=screen+1
			elif selected < viewmin: viewmin-=screen
			if viewmin < 0: viewmin=0
			erase_filelist(screen+2)
	except KeyboardInterrupt:
		if file_mode:
			line=original_line
			point=original_point
	finally:
		sys.stderr.write('\x1b[m\x1b[?25h\x1b[?7h') #default color, make cursor visible, enable line wrap
		erase_filelist(screen+2)
		termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
	if rerun:
		rerun_fn(line, point, icm)
	else:
		print line
		if not dmenu_mode:
			print point
 
def rerun_fn(line,point,icm=None):
	os.environ["READLINE_LINE"]=line
	os.environ["READLINE_POINT"]=str(point)
	if len(sys.argv) > 1:
		aliases=sys.argv[1]
	else:
		aliases="alias"
	if icm:
		os.execl(sys.argv[0],sys.argv[0],aliases,"rerun",icm[0],icm[1])
	else:
		os.execl(sys.argv[0],sys.argv[0],aliases,"rerun")
 
# Thanks to http://bytes.com/topic/python/answers/453313-best-way-finding-terminal-width-height
def ioctl_GWINSZ(fd): #### TABULATION FUNCTIONS
	try: ### Discover terminal width
		cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
	except:
		return None
	return cr
def terminal_size():
### decide on *some* terminal size
	# try open fds
	cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
	if not cr:
		# ...then ctty
		try:
			fd = os.open(os.ctermid(), os.O_RDONLY)
			cr = ioctl_GWINSZ(fd)
			os.close(fd)
		except:
			pass
	return int(cr[0]), int(cr[1])
 
def complete_command(workstr):
	paths=os.environ["PATH"].split(":")
	paths.append("COMPLETE_ALIASES")
	suggestions=[]
	for path in paths:
		suggestions.extend(complete_filename(workstr, path))
	return suggestions
def complete_filename(workstr, path):
	if path == "": path="./"
	path=os.path.expandvars(os.path.expanduser(path))
	suggestions=[]
	try:
		if path == "COMPLETE_ALIASES":
			if len(sys.argv) > 1:
				filelist=sys.argv[1].split("\n") #expect a newline separated list on argument 1
			else:
				return []
		else:
			filelist=os.listdir(path)
		for file in filelist:
			try:
				asterisk=re.escape(workstr)
				asterisk=re.sub("\\\\\*",".*",asterisk)
				asterisk=re.sub("\\\\\?",".?",asterisk)
				asterisk+=".*"
				asterisk_match=re.match(asterisk,file,re.I)
				if asterisk_match:
					suggestions.append(file)
				else:
					asterisk_match=re.match(asterisk,fixshell(file),re.I)
					if asterisk_match:
						suggestions.append(file)
			except ValueError: pass
	except OSError: pass
	return suggestions
def grep_list(patterns, lines):
	good_list=[]
	for line in lines:
		found=True
		for pattern in patterns:
			if pattern.lower() not in line.lower():
				found=False
				break
		if found: good_list.append(line)
	return good_list
 
def show_filelist(filedict, selected, viewmin, screen):
	length=len(filedict)-1
	eofs=viewmin+screen
	if eofs > length:
		modeofs=length
	else:
		modeofs=eofs
	try:
		if length % screen != 0:
			modlen=(screen-(length%screen)+length)
		else:
			modlen=length
	except ZeroDivisionError:
		modlen=1
	try:
		dotstart=screen*viewmin/modlen+viewmin
		if dotstart == 2: dotstart=1
		dotend=screen*(eofs+1)/modlen+viewmin-1
		if modeofs - viewmin == 0: modeofs=2
		selindicator=dotstart + (dotend - dotstart + 1) * (selected - viewmin) / (modeofs - viewmin +1)
	except ZeroDivisionError:
		dotstart=1
		dotend=1
		selindicator=1
	if selindicator > eofs: selindicator=eofs
	if dotend < dotstart: dotend=dotstart
	for i in xrange(viewmin, viewmin+screen+1):
		sys.stderr.write("\x1b[m")
		if i<dotstart or i>dotend:
			sys.stderr.write("  ")
		elif i == selindicator:
			sys.stderr.write("X ")
		elif i >= dotstart and i <= dotend:
			sys.stderr.write("* ")
		try:
			if i == selected:
				format_string=filedict[i]["format"].replace("\x1b[m","\x1b[m\x1b[30;46m")+ "\x1b[36;46m" + " # " * 99
			else:
				format_string=filedict[i]["format"]
			sys.stderr.write(format_string.replace("\n","(nl)")+"\x1b[m")
		except IndexError: pass
		if i != viewmin+screen: sys.stderr.write('\n')	
 
def erase_filelist(screen):
	for unused in xrange(screen):
		sys.stderr.write("\x1b[2K\x1b[A")
	sys.stderr.write("\x1b[2K\r")
 
def unfixshell_singlequote(goodstr):
	badstr=re.sub("'\\\\''", "'", goodstr)
	if badstr[-1] == "'":
		return badstr[1:-1]
	else:
		return badstr[1:]
def unfixshell(goodstr):
	if len(goodstr) != 0 and goodstr[-1] == "\\":
		appendslash="\\"
	else:
		appendslash=""
	goodpieces=[]
	while "\\\\" in goodstr:
		index=goodstr.index("\\\\")
		goodpieces.append(goodstr[:index])
		try:
			goodstr=goodstr[index+2:]
		except IndexError: goodstr=""
	goodpieces.append(goodstr)
	goodstr=""
	for piece in goodpieces:
		goodstr=goodstr+re.sub("\\\\","",piece)+"\\"
	return goodstr[:-1]+appendslash
def fixshell(badstr):
	badchars=""" !@#$^&*()`'"<>[]{};:\\=?|	"""
	goodstr=""
	for ch in badstr:
		if ch in badchars:
			ch="\\"+ch
		goodstr=goodstr+ch
	return goodstr
 
def isrecommended(cmd, file, isdir):
	if cmd in ("cd","popd","rmdir"):
		return isdir
# http://wiki.archlinux.org/index.php/Common_Applications
# http://wiki.archlinux.org/index.php/Lightweight_Applications
# not sure if some of the binaries are correctly named
 
#Video (and audio)
	if cmd in ("mplayer", "mwrap", "vlc", "gmplayer", "smplayer", "mencoder", "kmplayer", "Parole", "whaawmp", "dragonplayer","ffmpeg"): 
		return re.search("\.(mkv|m4v|mpe?g|avi|mp4|wmv|rmvb|as[fx]|divx|vob|ogm|rm|flv|part|iso|mp?|ogg|wav|flac|m4a)$",file,re.I) != None
 
#Audio
	if cmd in ("mpg123", "mpg321", "mp3blaster", "cmus", "cplay", "moc", "xmms", "xmms2", "sonata", "deadbeef","ogg123"):
		return re.search("\.(mp?|wav|ogg|gsm|dct|flac|au|aiff|vox|wma|aac|ra|m4a)$",file,re.I) != None
 
#PDF
	if cmd in ("xpdf","epdfview","evince","foxit","mupdf","okular","apvlv","zathura"):
		return re.search("\.pdf$",file,re.I) != None
 
#Images
	if cmd in ("feh","geeqie","gqview","eog","gpicview","gthumb","mirage","qiv","ristretto","xnview","xv","viewnior"):
		return re.search("\.(jpe?g|png|gif|tiff|bmp|ico?n|tif)$",file,re.I) != None
 
#Games
	if cmd in ("sdlmame","openmsx","zsnes","desmume","VirtualBoy"):
		return re.search("\.(rom|dsk)$",file,re.I) != None
 
#Wine
	if cmd in ("wine", "winewrap", "wineconsole"):
		return re.search("\.(exe|com|bat)$", file, re.I) != None
 
#Archives
	if cmd in ("atool","x","xi","gunzip","extract","unzip","unrar","zip","rar","7z", "comix", "v"):
		return re.search("\.(tgz|zip|rar|bz2|gz|tar|exe|pk3|lha|Z|lzma)$",file,re.I) != None
 
#Text
	if cmd in ("vim","nano","acme","beaver","geany","leafpad","medit","mousepad","pyroom","sam","vi","gvim","emacs","tea","scite"):
		return re.search("\.(pdf|rom|dsk|jpe?g|png|gif|tiff|bmp|ico?n|tif|pdf|wav|ogg|gsm|dct|flac|au|aiff|vox|wma|aac|ra|mkv|mpe?g|avi|mp4|wmv|rmvb|as[fx]|divx|vob|ogm|rm|flv|part|iso|mp.|tgz|zip|rar|bz2|gz|tar|exe|pk3|lha|Z|lzma|\.o)$",file,re.I) == None and not isdir #everything else
 
	return False
 
main()

Pour installer cet outil voici comment vous devez procéder.

wget http://www.projet-libre.org/files/KingBash-last
chmod +x KingBash-last
sudo mv KingBash-last /usr/bin/KingBash

Enfin il ne reste plus qu’à ajouter les lignes ci-dessous à votre fichier .bashrc (dans votre home)

# Auto Complétion dans le style Ncurse avec la touche [TAB]
function kingbash.fn() {
  echo -n "KingBash> $READLINE_LINE" #Where "KingBash> " looks best if it resembles your PS1, at least in length.
  OUTPUT=`/usr/bin/KingBash "$(compgen -ab -A function)"`
  READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
  READLINE_LINE=`echo "$OUTPUT" | head -n -1`
  echo -ne "\r\e[2K"; }
bind -x '"\t":kingbash.fn'

Et depuis la version 19 du 06/08/2010 la touche % affiche un historique des commandes déjà saisies.
Pour que cette fonction soit disponible vous devez ajouter les lignes suivantes dans votre ~/.bashrc

# Historique pour KingBash avec la touche Ctrl+r
function kingbash.hs() {
 history -a
 echo -n "KingBash> $READLINE_LINE"
 OUTPUT=`KingBash -r <(tac ~/.bash_history)`
 READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
 READLINE_LINE=`echo "$OUTPUT" | head -n -1`
 echo -ne "\r\e[2K"; }
bind -x '"\x12": kingbash.hs'

L’outil est maintenant installé et fonctionnel, lorsque vous souhaiterez utiliser la touche [TAB] pour compléter le nom d’un fichier ou d’un dossier, une liste des suggestions apparaitra comme dans l’exemple sur la capture ci-dessous (il est possible de naviguer entre les différentes suggestions à l’aide des touches PgUP et PgDOWN.

kingBash

J’utilise cet outil depuis ce matin et je pense sérieusement l’adopter pour une utilisation quotidienne car il facilite grandement la navigation en ligne de commande.

NB1 : Le script KingBash dépend de python-lxml pour fonctionner

Debian/ubuntu :

sudo apt-get install python-lxml

ArchLinux :

sudo pacman -S extra/python-lxml

NB2 : Pour les utilisateurs d’ArchLinux l’installation depuis AUR est possible grâce à ce PKGBUILD.

Pour obtenir de l’aide lancez KingBash sans argument.

Usage
Tab Completion:
 
function kingbash.fn() {
  echo -n "KingBash> $READLINE_LINE" #Where "KingBash> " looks best if it resembles your PS1, at least in length.
  OUTPUT=`/usr/bin/KingBash "$(compgen -ab -A function)"`
  READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
  READLINE_LINE=`echo "$OUTPUT" | head -n -1`
  echo -ne "\r\e[2K"; }
bind -x '"\t":kingbash.fn'
 
 
History search:
 
function kingbash.hs() {
  echo -n "KingBash> $READLINE_LINE" #Where "KingBash> " looks best if it resembles your PS1, at least in length.
  history -a
  OUTPUT=`/usr/bin/KingBash -r <(tac ~/.bash_history)`
  READLINE_POINT=`echo "$OUTPUT" | tail -n 1`
  READLINE_LINE=`echo "$OUTPUT" | head -n -1`
  echo -ne "\r\e[2K"; }
bind -x '"\x12":kingbash.hs'
 
 
CLI dmenu:
 
... | /usr/bin/KingBash -r <(cat) | head -n 1 | ...
 
 
GUI dmenu:
 
rm /tmp/menu
cat > /tmp/inmenu
urxvtc -e bash -c 'export READLINE_POINT=0; answ=$(/usr/bin/KingBash -r /tmp/inmenu | head -n 1); echo -n "$answ" > /tmp/menu'
while sleep 0.1; do [ -f /tmp/menu ] && break; done
cat /tmp/menu
rm /tmp/menu
rm /tmp/inmenu
-------
 
F1 inside the application will print a key table

Comme l »indique la dernière consigne, il suffit de taper F1 pour obtenir de l’aide sur les raccourcis existants

There are two modes: Tab completion and History/file/dmenu completion.
---Key table---
+Both modes+
 F1             This help
 Up/Down
 Shift+Up/Down
 Page up/Pagedown
 Home/End       Move around the list
 Enter          Complete the selection and quit
 Any other character is added "as is" (with the escape sequence replaced with ESC).
 Under "Tab completion" the program quits after a space or equals sign.
 
+Tab Completion+
*F2             Erase first word and move cursor to start of line, after the selection has been completed
 Left           Go to the parent directory and continue browsing
 Right          Complete the selection, but if it's a directory, bring up the program again inside that directory
 Escape         Quit, leaving the line as it is seen in the application
 Backspace      Erase the character left of the cursor and complete again
 Alt+Backspace  Same, but an entire word or path
 Control+U      Clear the line and quit
 Insert         Complete the selection, move the selector bar down, and continue as if we are completing the previous selection again
*Asterisk       Add everything in the list to the command line. If there are 'suggestions', only complete those. Quit afterwards.
 
+History Completion+
 Left           Move the cursor left
 Right          Move the cursor right
 Escape         Quit, restore the line to what it was when KingBash started
 Backspace      Erase the character left of the cursor
 Alt+Backspace  Same, but an entire word or path
*Delete         Delete the character under the cursor
 Control+U      Clear the line and continue
*Tab            Make the current line the same as the selection
 Insert         Like Tab
 
* means this key does nothing at all in the other mode

Trackback URL

, , , ,

5 Comments on "Bash : navigateur de fichiers (Ncurse like) pour l’auto complétion"

  1. inalgnu
    06/08/2010 at 1 h 54 min Permalink

    Vraiment cool ce genre d’outil merci pour le partage : ) je viens de l’installer sous Fedora, ça fonctionne très bien. Juste une question, il est sous quelle licence? j’ai pas trouvé ça. merci

  2. Jérôme
    06/08/2010 at 2 h 47 min Permalink

    Pour la licence je n’ai pas trouvé non plus, sur la page du PKGBUILD on voit « License: none ».
    Et vu que le code est posté sur un Pastebin je pense qu’on peut dire GPL :)

    Un autre outil sympa pour donner de la couleur dans le terminal cope wrapper et un petit file manager en ligne de commande bien sympa, ranger

    Et pour rappel une petite modif de $PS1 et l’ajout de quelques alias au ~/.bashrc et la ligne de commande prend une autre dimension ;o)

  3. arn0
    10/01/2012 at 3 h 00 min Permalink

    Merci bien je ne comprends tout semble fonctionner sous ubuntu sauf la touche F1 une idée ? Par avance merci

Trackbacks

  1. [...] This post was mentioned on Twitter by projetlibre, Jérôme Launay. Jérôme Launay said: KingBash: un navigateur de fichiers pour ...

  2. [...] Pour une meilleure ergonomie et afin d’améliorer encore votre productivité, je ne peux que vous inciter à installer kingbash ...

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Subscribe to Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes