首页 > Elisp, 中级 > 用elisp编译解释当前的buffer

用elisp编译解释当前的buffer

2010年3月5日 ahei 发表评论 阅读评论

作者: laihj

运行当前的buffer,就是说编译或解释当前的buferr。比如在编辑的是python文件”hello.py”,那么运行它的命令就是”python hello.py”,一般的python-mode用”C-c C-c”来处理这个问题,在编辑过程中可以调用这个快捷键来运行。当然你也可以使用”M-!”来打开shell command的mini buffer来输入命令。

诚然,很多语言的mode里面实际上都内置了这一功能,但我觉得,一方面不同的mode可能定义不同快捷键,造成了额外的记忆负担,另一方面并不能要求所有的mode都提供这一功能,在mode不完整的情况下你大概也需要自己定义的能力。

要做这事儿,当然是自定义一个函数。那么最直观的想法,就是在elisp里面写一行调用shell来执行命令的代码。是的,有这种东西,示例如下:

(shell-command "python hello.py")

这一行代码的相当于在终端中执行”python hello.py”。

我们的目的是执行当前buffer,所以下一步要做的是得到当前buffer所对应的文件名。在上一篇blog中介绍过相关方法,就是”buffer-file-name”。

于是代码就变成了这样。

(shell-command (concat "python " (buffer-file-name)))

用concat把”python “和当前buffer的文件名连起来作为要执行的命令。

至此,就完成了.py文件的执行函数,那推广之,需要对不同的文件进行编译/解释时,就需要扩展这个命令。

我们知道对.sh文件要用bash命令执行,对.py要用python,对.htm要调用firefox。现在要做的就是让机器知道这件事。很明显的,我们需要一个map,把它们对应地存下来。

完整的代码和注释如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(defun run-current-file ()
(interactive)
(let (ext-map file-name file-ext prog-name cmd-str
(setq ext-map
         '(
            ("py" . "python")
            ("sh" . "bash")
            ("htm" . "firefox")
            )
          );定义命令-文件类型映身表.
    (setq file-name (buffer-file-name));得到当前的buffer名
    (setq file-ext (file-name-extension file-name));得到后缀
    (setq prog-name (cdr (assoc file-ext ext-map)));根据后缀得到执行的命令,通过对ext-map的查找
    (setq cmd-str (concat prog-name " " file-name));拼出一个命令
    (shell-command cmd-str)));执行

完毕,为这个函数绑定一个键,在编辑相应文件的时候调用,就可以对其进行需要的操作了,不仅限于编译和解释,实际上很容易看出来,只要shell能支持的,你可以玩。当然,要有权限。

Have Fun!

分享家:Addthis中国
GD Star Rating
loading...
用elisp编译解释当前的buffer, 7.2 out of 10 based on 5 ratings 标签:buffer, Elisp, laihj, lisp, mode, python, 扩展, 编译, 配色

相关日志

分类: Elisp, 中级
  1. ann77
    2010年3月5日08:58 | #1

    以前和 ahei 讨论过高阶函数的东西。我重写你的例子如下

    (defvar run-current-file-alist
    ‘((“py” . “python”)
    (“sh” . “bash”)
    (“htm” . “firefox”)))
    (defun run-current-file ()
    (interactive)
    (funcall
    (\. #’shell-command
    ($ (wlflip ($ mapconcat #’identity)) ” “)
    ($ (wlflip list) buffer-file-name)
    cdr
    ($ (wlflip assoc) run-current-file-alist)
    file-name-extension
    ($ buffer-file-name)
    )))

    评论不能格式化代码,copy paste 之后 C-M-\ 吧
    关于 wlcompose.el 参考 http://www.emacswiki.org/emacs/Wang_ChunYe

    [回复]

    ahei 回复:

    @ann77, 好复杂阿,看来我要学习的东西还有很多阿

    [回复]

  2. filebat
    2010年4月3日15:24 | #2

    十分handy的功能,学习学习

    做了几个小的改进:
    - 当对于不预知的文件类型不做处理
    - 文件名的全路径中有可能有空格,使用”将文件名括起来
    - 通过cond做switch选择来简化代码

    ;; ————————– separator ————————–
    (defun run-current-file ()
    (interactive)
    (setq file_name (buffer-file-name))
    (setq file_ext (file-name-extension file_name))
    (setq prog_name
    (cond ((string= file_ext “py”) “python”)
    ((string= file_ext “sh”) “bash”)
    (t “”)))

    (unless (string= prog_name “”)
    (progn
    (setq cmd_str (format “%s ‘%s’” prog_name file_name))
    (message cmd_str)
    ;;(shell-command cmd_str)
    ))
    )

    [回复]

    ahei 回复:

    @filebat, good

    [回复]

    filebat 回复:

    @ahei, 你博文对emacs的介绍通俗易懂, 值得我们好好学习。

    [回复]

    ahei 回复:

    谢谢, 都是靠众作者的一起努力, 还要靠大家的支持.

    [回复]

    filebat 回复:

    @filebat,

    上面的代码貌似还是有些小问题

    如果打开的文件是tramp打开的,不知道全路径名是不是会带上”/root@10.32.189.13:/tmp/1.py”之类的。
    这样的话,貌似只能取短文件名才行。

    [回复]

    ahei 回复:

    @filebat, 感觉tramp操作远程文件还是有点卡的, 不如直接ssh上去用emacs, 而且即使不能ssh上去, 还不如直接down下来修改, 呵呵, 我一般都不用tramp

    [回复]

    filebat 回复:

    @ahei,
    远程ssh上的电脑一般没有我们配置好的emacs, 所以不太方便。 tramp貌似第一次比较卡,之后都还好。

    [回复]

    ahei 回复:

    @filebat, 呵呵, 我一般都把配置文件放到svn上, 直接在远程svn up就可以了.

    [回复]

    filebat 回复:

    @ahei,

    可能是我太吹毛求疵了, 关键是要登录的是客户或QA的机器。

    [回复]

    ahei 回复:

    @filebat, 哦, 那样是麻烦了点.

    [回复]

  3. xilbert
    2010年5月30日10:28 | #3

    确实是个很实用的设置,根据此修改了一下,将shell-command 修改为compile,这样当编译出问题时,就可以点击错误,跳转到发生错误的行。我将编译绑定到F5,只有按F5,就能编译c 、c++、python、perl、emacs-lisp等。
    ;;系统安装了cygwin,gcc 不能使用windows路径,要先装化为cygwin型路径。
    (defun change-to-cygwin-style-path (full-path)
    (let ((file-full-path nil) (disk nil) (left nil) (cygwin-style-file-path nil))

    (setq file-full-path full-path)
    (setq disk (substring file-full-path 0 1))
    (setq left (substring file-full-path 2 (length file-full-path)))
    (setq cygwin-style-file-path (concat “/cygdrive/” disk left))))

    (defun xilbert-compile ()
    (interactive)
    (let ((mode major-mode)
    (compstr nil))

    (cond ((eq mode ‘c-mode)
    (setq compstr (concat “gcc -std=\”c99\” ” (change-to-cygwin-style-path (buffer-file-name)))))
    ((eq mode ‘c++-mode)
    (setq compstr (concat “c++ ” (change-to-cygwin-style-path (buffer-file-name)))))
    ((eq mode ‘emacs-lisp-mode)
    (emacs-lisp-byte-compile))
    ((eq mode ‘python-mode)
    (setq compstr (concat “python ” (buffer-file-name)))
    )
    ((eq mode ‘cperl-mode)
    (setq compstr (concat “D:/Perl/bin/perl.exe ” (buffer-file-name))))
    )
    (save-buffer)
    (if compstr
    (compile compstr))))

    (global-set-key [(f5)] ‘xilbert-compile)

    初学emacs-lisp,写得不好,只是能用而已,希望高手指点!

    [回复]

    ahei 回复:

    @xilbert, 不错不错

    [回复]

    xilbert 回复:

    @ahei,
    站长好,看了你们这些作者这么用心地在写文章,我也有点想写点文章,虽然水平有限,但想到
    能让更多地人了解这么好的软件就管不了那么多了,而且通过写文章如果能让你们这些高手指点一二
    进步也会更快。不知在emacser上怎么发文章?

    [回复]

    ahei 回复:

    非常欢迎.你加我的msn/gtalk就是了,或者直接把文章发到我邮箱,我的联系方式在这里

    [回复]

    xilbert 回复:

    @ahei,
    哈哈,谢谢啦!

    [回复]

  4. onixie
    2010年8月23日08:38 | #4

    是不是还应该分析一下文件开头的#!。
    也许有些没有扩展名的文件也是可执行的脚本(例如configure)

    [回复]

  5. 2016年4月7日07:39 | #5

    School officials have begun a capital campaign to raise money for the project, which includes debt retirement. So far, they have raised $1.5 million through donations. http://www.cheapchinajerseysnfl.us.org Saturday and 6 p. f coach outlet online
    Boxes to benefit from good environmental profile o.westboroughpolice.com The complaint alleges Black Weapons Armory, which no longer is in business, and Rompel took payments for firearms and failed to deliver those firearms to consumers, states a news release.
    Tulane head coach Lisa Stockton cheers her team on against Connecticut in the first half of an NCAA women’s college basketball game in New Orleans, Monday, Feb. 23, 2015. (AP Photo/Bill Haber) http://www.raybansunglassesebay.us.com There are so many families who don’t. a ray ban outlet
    But “it certainly adds weight to the argument,” he said coach outlet store online FILE – In this April 23, 2010 photo, best-selling author Neil Gaiman, 49, poses in his writing gazebo at his home in western Wisconsin.
    o Nicholas A. Donovan to Sally O. Emerson and William E. Emerson, Holcomb Road, $27,000. http://www.coachhandbags.com.co There were 119 homes sold in Faulkner County in December, up 60. http://www.raybanoutlet.name
    The homepage features sweeping video with a bird s eye view of nature s majesty as well as a dynamic new promotional reel. coach outlet store online The game didn’t have much defense, but the winning score was a defensive play. http://www.coachhandbagsdeal.us.com
    Wells Fargo Bank, trustee, to Petr Privedenyuk, 85 Pembroke St., $48,000. nfl jerseys Patrick’s Day observances in North Little Rock and Little Rock will be Saturday, starting with a parade and a free “familyfriendly” festival, organizers of the events announced. i coach outlet store online
    Paritaprevir was discovered during the ongoing collaboration between AbbVie and Enanta Pharmaceuticals (NASDAQ: ENTA) for hepatitis C protease inhibitors and regimens that include protease inhibitors. coach factory outlet “He was asked about four years of man-to-man challenges against Tarczewski, and how he saved the best for last.
    Way to be prepared, Phoenix!The cost for an autograph from Leonard Nimoy was a steep $75. michael kors online And they want something coolerlooking than a minivan, without the size of a truck.
    The difference this time was that the Thunder continued to play well to hold on for a very convincing victory. coach outlet online gov/flu or call your doctor or local health department.
    Brazilian state prosecutors filed money laundering charges against ex-president Luiz Inacio Lula da Silva in a dramatic twist to an anti-corruption battle threatening to bring down the government. michael kors online The Democratic and Republican parties have woken up to the fact that, according to the State Department, 7.
    c This is an ongoing battle. coach handbags Richard Childress Racing gave Ryan Newman two tires, while Harvick crew chief Rodney Childers made the risky call for four tires.
    The Bentayga beguiled me. michael kors bags To enter, email your name and phone number to , subject line Steve Earle. o coach outlet store
    “We are beginning to be heard and we are gaining. louis vuitton handbags With her cardboard cards and her oatmeal boxes, Inge registered the velocity of propagation of the earthquakes to all parts of the globe.
    x Portland’s wacky run up to the 2016 election just got a little more interesting: Jules Bailey, an on-the-rise Multnomah County commissioner and former state lawmaker, will run for mayor. ray ban sunglasses “But other than that, it was good racing. y
    March 24 Horizon Middle School, 3915 S. http://www.michaelkorsbag.us.org Elliott is wearing black-rimmed glasses. ray ban sunglasses
    “Strong demand for our vehicles provided another double-digit sales increase in October, and Ford vehicles posted all-time record average transaction pricing of $34,600 per vehicle,” Mark LaNeve, Ford vice president of U.S. marketing, sales and service, said in a release. “Gains in our truck business were especially strong, with F-Series delivering its fourth straight month of sales gains and its best October retail levels since 2004.” michael kors outlet I think we all need to rally and make sure that what we sell will grow when we sell it or where it will be planted. x http://www.louisvuittonhandbagsbuy.co.uk
    “All parties involved have put us in this situation,” Haste said http://www.coachhandbags.net.co p style text-align: center;”Thirteen-mile RangeThe range of the Arizona’s guns is from 12 to 13 miles as they will be set in her turrets, or as far as her gun-pointers and observers can see in brightest weather.
    Queener said most of the district’s urban renewal projects have involved building transportation infrastructure, such as the Sunnybrook Road overpass over Interstate 205. ray ban sunglasses A: I mean authenticity for authenticity’s sake doesn’t really matter: There are plenty of great period films. n michael kors handbags
    “I’ve talked to a few guests who have said ‘wine week is coming up, what do you have going on?’ So that I think is the really important piece of the puzzle,” he said recently by phone. coach handbags Anze Kopitar threw the puck in front, where Gaborik redirected it through Crawford’s legs.

    [回复]

  6. 2016年4月7日11:52 | #6

    Kento Oudomphong, Grant, senior michael kors handbags Most are blooming and setting seeds for next year. z coach outlet
    Brooke-Marciniak. coach factory outlet It’s less than 50 miles from a metro area of 1 million, but it’s remarkably empty of man-made intrusions.
    He said it was not surprising that the results were negative because by the time health authorities hear about an outbreak the tainted food has often already been used. http://www.coachfactorysoutlet.com And we need to do more to make sure religious exemptions do not prevent women from accessing comprehensive reproductive care, including abortion and contraception. c coach outlet store online
    “Favorite Mardi Gras experience: “The pet parade over in Fairhope. coach outlet online The sprawling district runs from Tucson’s northern suburbs east to the New Mexico line and Flagstaff, taking in large tribal areas.
    x “A Gift Wrapped Christmas” (2015), 8 p.m. Nov. 28, Lifetime. ray ban sunglasses It is a musty relic of another time, a Debbie Reynolds musical. michael kors outlet online
    “Norma Jean Higuera-Trask — a civics teacher at Challenger Middle School and a coach for the We the People program, which helps students become informed citizens — said the traveling oral argument was a unique experience for her students. http://www.cheapjordanshoes.us.org The complaint alleges that Officer Phillip Mitchell Brailsford’s use of deadly force was not justified when he shot 26-year-old Daniel Shaver at the La Quinta Inn near U. http://www.michaelkorshandbagsrack.us.com
    “Coffee is so much more complicated than wine,” Higgins says. “It’s not just the terroir, it’s the physical conditions, the water, the phosphoric acids. Is the farmer passionate? The farm is a machine. The producer can really choose to whip the racehorse and make it whip, or go at a gallop, and all of these things change the product, and it’s all tied to the economy. michael kors outlet He is Independent anyway. q http://www.michaelkors.us.org
    Players, fans and medical professionals see the game in different ways, but that doesn’t mean their viewpoints have to conflict without anyresolution louis vuitton handbags Winer said that as in the Marcy case, Berkeley’s Office for the Prevention of Harassment and Discrimination concluded his client’s complaints were credible and that Choudhry’s behavior had violated campus sex harassment policies.
    It’s threatening to people if you love yourself. http://www.michaelkors.us.org The Royals’ Edinson Volquez allowed one run in the first inning in an otherwise tidy spring training debut, though the Texas Rangers went on to rout Kansas City 100.
    Stresses in the centre of a tectonic plate can also result in earthquakes. coach factory outlet “The race featured an event-record 33 lead changes, and Johnson expected there would be one more, but on a slippery day on the smallest circuit in NASCAR’s premier series, the cars at the end weren’t conducive to typical short-track racing.
    Depriving yourself of the foods you enjoy will only set you up to eat like the Nutty Professor later. louis vuitton outlet Day is the first makeup day in case of snow.
    w Order of Athena, 10:30 a. coach outlet store online MARANA 7, MOUNTAIN VIEW 2At MaranaSingles S.
    “The deputy came around a bend in the 3200 block and saw a blue metal bat in the roadway. oakley sunglasses Trusted wine countries where even the lowliest box wine isn’t all that unpalatable — at least for poor college students. e michael kors outlet online
    But education is only part of the equation. coach outlet If Anzar has its share of flaws, as most campuses do, then district officials should identify and address those issues and make sure every student who walks through the school’s doors has a fair shake at a decent education.
    t The 260-acre Monterey Lake offers 104 docks, fishing, boating and swimming beaches. Pontoon boats are the most popular watercraft on the lake. http://www.michaelkorshandbags.us.org March 6 and 13, South Arkansas Arts Center, 110 E. h
    Raj Sachdave MCIPS, Head of Auxiliary Partnerships Innovation, Capita Travel and Events, said: “Business travellers needs and expectations are constantly evolving. cheap nfl jerseys Isuppose that means a journey to the Texas Roadhouse and itsbig-screen TVs can’t be avoided. http://www.coachhandbags.com.co
    Police said they made four arrests and one officer suffered a dislocated shoulder when the crowd interfered with an arrest at the Pacific Place shopping area. The police said about 700 people took part in the demonstration, one of many around the country. michael kors outlet What do you get when you bring together five guys playing a blend of rock, funk and reggae music, putting instruments in schools through charity and traveling to the Midwest for the first time in a semireliable van? You get the Brothers Gow, a band from San Diego, in the middle of a twomonth winter 2016 tour. w coach outlet
    Granada Ave. http://www.michaelkorsbags.me We are thankful to the fantastic support we received from students, parents and the community for each of our East Valley schools, as well and look forward to that spirit continuing in the upcoming academic year.
    While the No. 25 Ducks looked strong in the Monday win over Baylor, Altman is focused on development over the coming weeks. Sophomore forward Jordan Bell is still expected to miss a couple of weeks, while Altman said senior guard Dylan Ennis will still be out for quite some time. The Ducks primarily used six players against the Bears, and Altman will be looking to players like Kendall Small, Trevor Manuel and Roman Sorkin to first show him something during practice and then translate it in a game atmosphere. coach outlet store The term ruck or rucking comes from the common use of a military rucksack or, in laymen’s terms, a backpack, to carry weight. n oakley outlet
    “Because of that, they have a higher standard of conflict than legislators,” she continued. michael kors outlet Mountain View at Sahuaro, 4 p.

    [回复]

  1. 本文目前尚无任何 trackbacks 和 pingbacks.
:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: